repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
micolous/metrodroid
refs/heads/master
native/metrodroid/metrodroid/ViewController.swift
gpl-3.0
1
// // ViewController.swift // // Copyright 2019 Google // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // import UIKit import CoreNFC import metrolib class ViewController: UIViewController { var reader: NFCReader? override func viewDidLoad() { super.viewDidLoad() updateObfuscationNotice() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateObfuscationNotice() } @IBAction func scanButton(_ sender: UIButton) { reader = NFCReader() reader!.start(navigationController: navigationController) } @IBAction func preferencesButton(_ sender: UIButton) { Utils.openUrl(url: UIApplication.openSettingsURLString) } @IBOutlet weak var obfuscationLabel: UILabel! private func updateObfuscationNotice() { let hasNfc = NFCTagReaderSession.readingAvailable let obfuscationFlagsOn = (Preferences.init().hideCardNumbers ? 1 : 0) + (Preferences.init().obfuscateBalance ? 1 : 0) + (Preferences.init().obfuscateTripDates ? 1 : 0) + (Preferences.init().obfuscateTripFares ? 1 : 0) + (Preferences.init().obfuscateTripTimes ? 1: 0) if (obfuscationFlagsOn > 0) { obfuscationLabel.text = Utils.localizePlural( RKt.R.plurals.obfuscation_mode_notice, obfuscationFlagsOn, obfuscationFlagsOn) } else if (!hasNfc) { obfuscationLabel.text = Utils.localizeString(RKt.R.string.nfc_unavailable) } else { obfuscationLabel.text = nil } } }
d5f839ad7854fdabadfe574793cba06a
32.597015
86
0.664594
false
false
false
false
brave/browser-ios
refs/heads/development
Client/Frontend/Browser/ReaderModeBarView.swift
mpl-2.0
1
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Foundation import UIKit import SnapKit import Shared import XCGLogger private let log = Logger.browserLogger enum ReaderModeBarButtonType { case markAsRead, markAsUnread, settings, addToReadingList, removeFromReadingList fileprivate var localizedDescription: String { switch self { case .markAsRead: return Strings.Mark_as_Read case .markAsUnread: return Strings.Mark_as_Unread case .settings: return Strings.Reader_Mode_Settings case .addToReadingList: return Strings.Add_to_Reading_List case .removeFromReadingList: return Strings.Remove_from_Reading_List } } fileprivate var imageName: String { switch self { case .markAsRead: return "MarkAsRead" case .markAsUnread: return "MarkAsUnread" case .settings: return "SettingsSerif" case .addToReadingList: return "addToReadingList" case .removeFromReadingList: return "removeFromReadingList" } } fileprivate var image: UIImage? { let image = UIImage(named: imageName) image?.accessibilityLabel = localizedDescription return image } } protocol ReaderModeBarViewDelegate { func readerModeBar(_ readerModeBar: ReaderModeBarView, didSelectButton buttonType: ReaderModeBarButtonType) } struct ReaderModeBarViewUX { static let Themes: [String: Theme] = { var themes = [String: Theme]() var theme = Theme() theme.backgroundColor = UIConstants.PrivateModeReaderModeBackgroundColor theme.buttonTintColor = UIColor.white themes[Theme.PrivateMode] = theme theme = Theme() theme.backgroundColor = UIColor.white theme.buttonTintColor = UIColor.darkGray themes[Theme.NormalMode] = theme return themes }() } class ReaderModeBarView: UIView { var delegate: ReaderModeBarViewDelegate? var settingsButton: UIButton! @objc dynamic var buttonTintColor: UIColor = UIColor.clear { didSet { settingsButton.tintColor = self.buttonTintColor } } override init(frame: CGRect) { super.init(frame: frame) // This class is glued on to the bottom of the urlbar, and is outside of that frame, so we have to manually // route clicks here. See see BrowserViewController.ViewToCaptureReaderModeTap // TODO: Redo urlbar layout so that we can place this within the frame *if* we decide to keep the reader settings attached to urlbar settingsButton = UIButton() settingsButton.setTitleColor(BraveUX.BraveOrange, for: .normal) settingsButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: UIFont.systemFontSize - 1) settingsButton.setTitle(Strings.Reader_Mode_Settings, for: .normal) settingsButton.addTarget(self, action: #selector(ReaderModeBarView.SELtappedSettingsButton), for: .touchUpInside) settingsButton.accessibilityLabel = Strings.Reader_Mode_Settings addSubview(settingsButton) settingsButton.snp.makeConstraints { make in make.centerX.centerY.equalTo(self) } self.backgroundColor = UIColor.white.withAlphaComponent(1.0) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func draw(_ rect: CGRect) { super.draw(rect) let context = UIGraphicsGetCurrentContext() context!.setLineWidth(0.5) context!.setStrokeColor(red: 0.1, green: 0.1, blue: 0.1, alpha: 1.0) context!.setStrokeColor(UIColor.gray.cgColor) context!.beginPath() context!.move(to: CGPoint(x: 0, y: frame.height)) context!.addLine(to: CGPoint(x: frame.width, y: frame.height)) context!.strokePath() } @objc func SELtappedSettingsButton() { delegate?.readerModeBar(self, didSelectButton: .settings) } } //extension ReaderModeBarView: Themeable { // func applyTheme(themeName: String) { // guard let theme = ReaderModeBarViewUX.Themes[themeName] else { // log.error("Unable to apply unknown theme \(themeName)") // return // } // // backgroundColor = theme.backgroundColor // buttonTintColor = theme.buttonTintColor! // } //}
9a90ebf162740d86eea8f8de09467924
34.140625
140
0.68297
false
false
false
false
troystribling/BlueCap
refs/heads/master
Examples/CentralManager/CentralManager/SetUpdatePeriodViewController.swift
mit
1
// // SetUpdatePeriodViewController.swift // Central // // Created by Troy Stribling on 5/2/15. // Copyright (c) 2015 Troy Stribling. The MIT License (MIT). // import UIKit import BlueCapKit class SetUpdatePeriodViewController: UITableViewController, UITextFieldDelegate { @IBOutlet var updatePeriodTextField : UITextField! var characteristic : Characteristic? var isRaw : Bool? required init?(coder aDecoder:NSCoder) { super.init(coder:aDecoder) } override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if let isRaw = isRaw, let updatePeriod : TiSensorTag.AccelerometerService.UpdatePeriod = characteristic?.value() { if isRaw { updatePeriodTextField.text = "\(updatePeriod.rawValue)" } else { updatePeriodTextField.text = "\(updatePeriod.period)" } } updatePeriodTextField.becomeFirstResponder() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) } // UITextFieldDelegate func textFieldShouldReturn(_ textField: UITextField) -> Bool { if let enteredPeriod = self.updatePeriodTextField.text, let isRaw = isRaw, let value = UInt16(enteredPeriod), !enteredPeriod.isEmpty { let rawValue : UInt16 if isRaw { rawValue = value } else { rawValue = value / 10 } if let rawPeriod = UInt8(uintValue:rawValue), let period = TiSensorTag.AccelerometerService.UpdatePeriod(rawValue:rawPeriod) { let writeFuture = self.characteristic?.write(period, timeout: 5.0) writeFuture?.onSuccess {_ in textField.resignFirstResponder() _ = self.navigationController?.popViewController(animated: true) } writeFuture?.onFailure { [weak self] error in self?.present(UIAlertController.alertOnError(error), animated:true) { () -> Void in textField.resignFirstResponder() _ = self?.navigationController?.popViewController(animated: true) } } return true } else { return false } } else { return false } } }
b2fe5853535f91ae780eac68ce31e20b
33.652778
142
0.58998
false
false
false
false
ianbytchek/OAuthSwift
refs/heads/master
Sources/OAuthSwiftURLHandlerType.swift
mit
1
// // OAuthSwiftURLHandlerType.swift // OAuthSwift // // Created by phimage on 11/05/15. // Copyright (c) 2015 Dongri Jin. All rights reserved. // import Foundation #if os(iOS) || os(tvOS) import UIKit #elseif os(watchOS) import WatchKit #elseif os(OSX) import AppKit #endif @objc public protocol OAuthSwiftURLHandlerType { func handle(_ url: URL) } // MARK: Open externally open class OAuthSwiftOpenURLExternally: OAuthSwiftURLHandlerType { public static var sharedInstance: OAuthSwiftOpenURLExternally = OAuthSwiftOpenURLExternally() @objc open func handle(_ url: URL) { #if os(iOS) || os(tvOS) #if !OAUTH_APP_EXTENSIONS UIApplication.shared.openURL(url) #endif #elseif os(watchOS) // WATCHOS: not implemented #elseif os(OSX) NSWorkspace.shared().open(url) #endif } } // MARK: Open SFSafariViewController #if os(iOS) import SafariServices @available(iOS 9.0, *) open class SafariURLHandler: NSObject, OAuthSwiftURLHandlerType, SFSafariViewControllerDelegate { public typealias UITransion = (_ controller: SFSafariViewController, _ handler: SafariURLHandler) -> Void open let oauthSwift: OAuthSwift open var present: UITransion open var dismiss: UITransion /// retains observers var observers = [String: NSObjectProtocol]() open var factory: (_ URL: URL) -> SFSafariViewController = {URL in return SFSafariViewController(url: URL) } /// delegates open weak var delegate: SFSafariViewControllerDelegate? // configure default presentation and dismissal code open var animated: Bool = true open var presentCompletion: (() -> Void)? open var dismissCompletion: (() -> Void)? open var delay: UInt32? = 1 /// init public init(viewController: UIViewController, oauthSwift: OAuthSwift) { self.oauthSwift = oauthSwift self.present = { [weak viewController] controller, handler in viewController?.present(controller, animated: handler.animated, completion: handler.presentCompletion) } self.dismiss = { [weak viewController] _, handler in viewController?.dismiss(animated: handler.animated, completion: handler.dismissCompletion) } } public init(present: @escaping UITransion, dismiss: @escaping UITransion, oauthSwift: OAuthSwift) { self.oauthSwift = oauthSwift self.present = present self.dismiss = dismiss } @objc open func handle(_ url: URL) { let controller = factory(url) controller.delegate = self // present controller in main thread OAuthSwift.main { [weak self] in guard let this = self else { return } if let delay = this.delay { // sometimes safari show a blank view.. sleep(delay) } this.present(controller, this) } let key = UUID().uuidString observers[key] = OAuthSwift.notificationCenter.addObserver( forName: NSNotification.Name.OAuthSwiftHandleCallbackURL, object: nil, queue: OperationQueue.main, using: { [weak self] _ in guard let this = self else { return } if let observer = this.observers[key] { OAuthSwift.notificationCenter.removeObserver(observer) this.observers.removeValue(forKey: key) } OAuthSwift.main { this.dismiss(controller, this) } } ) } /// Clear internal observers on authentification flow open func clearObservers() { clearLocalObservers() self.oauthSwift.removeCallbackNotificationObserver() } open func clearLocalObservers() { for (_, observer) in observers { OAuthSwift.notificationCenter.removeObserver(observer) } observers.removeAll() } /// SFSafariViewControllerDelegate public func safariViewController(_ controller: SFSafariViewController, activityItemsFor URL: Foundation.URL, title: String?) -> [UIActivity] { return self.delegate?.safariViewController?(controller, activityItemsFor: URL, title: title) ?? [] } public func safariViewControllerDidFinish(_ controller: SFSafariViewController) { // "Done" pressed self.clearObservers() self.delegate?.safariViewControllerDidFinish?(controller) } public func safariViewController(_ controller: SFSafariViewController, didCompleteInitialLoad didLoadSuccessfully: Bool) { self.delegate?.safariViewController?(controller, didCompleteInitialLoad: didLoadSuccessfully) } } #endif // MARK: Open url using NSExtensionContext open class ExtensionContextURLHandler: OAuthSwiftURLHandlerType { fileprivate var extensionContext: NSExtensionContext public init(extensionContext: NSExtensionContext) { self.extensionContext = extensionContext } @objc open func handle(_ url: URL) { extensionContext.open(url, completionHandler: nil) } }
7909922f9a0453131c2ae25b6841efe1
32.377246
150
0.609616
false
false
false
false
Witcast/witcast-ios
refs/heads/develop
Pods/Material/Sources/Frameworks/Motion/Sources/Animator/MotionCoreAnimationViewContext.swift
apache-2.0
1
/* * The MIT License (MIT) * * Copyright (C) 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Original Inspiration & Author * Copyright (c) 2016 Luke Zhao <[email protected]> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ import UIKit internal class MotionCoreAnimationViewContext: MotionAnimatorViewContext { /// The transition states. fileprivate var transitionStates = [String: (Any?, Any?)]() /// A reference to the animation timing function. fileprivate var timingFunction = CAMediaTimingFunction.standard /// Layer which holds the content. fileprivate var contentLayer: CALayer? { return snapshot.layer.sublayers?.get(0) } /// Layer which holds the overlay. fileprivate var overlayLayer: CALayer? override func clean() { super.clean() overlayLayer = nil } override class func canAnimate(view: UIView, state: MotionTransitionState, isAppearing: Bool) -> Bool { return nil != state.position || nil != state.size || nil != state.transform || nil != state.cornerRadius || nil != state.opacity || nil != state.overlay || nil != state.backgroundColor || nil != state.borderColor || nil != state.borderWidth || nil != state.shadowOpacity || nil != state.shadowRadius || nil != state.shadowOffset || nil != state.shadowColor || nil != state.shadowPath || nil != state.contentsRect || state.forceAnimate } override func apply(state: MotionTransitionState) { let ts = viewState(targetState: state) for (key, targetValue) in ts { if nil == transitionStates[key] { let current = currentValue(for: key) transitionStates[key] = (current, current) } animate(key: key, beginTime: 0, fromValue: targetValue, toValue: targetValue) } } override func resume(at elapsedTime: TimeInterval, isReversed: Bool) { for (key, (fromValue, toValue)) in transitionStates { transitionStates[key] = (currentValue(for: key), !isReversed ? toValue : fromValue) } targetState.duration = isReversed ? elapsedTime - targetState.delay : duration - elapsedTime animate(delay: max(0, targetState.delay - elapsedTime)) } override func seek(to elapsedTime: TimeInterval) { seek(layer: snapshot.layer, elapsedTime: elapsedTime) if let v = contentLayer { seek(layer: v, elapsedTime: elapsedTime) } if let v = overlayLayer { seek(layer: v, elapsedTime: elapsedTime) } } override func startAnimations(isAppearing: Bool) { if let beginState = targetState.beginState?.state { let appeared = viewState(targetState: beginState) for (k, v) in appeared { snapshot.layer.setValue(v, forKeyPath: k) } if let (k, v) = beginState.overlay { let overlay = getOverlayLayer() overlay.backgroundColor = k overlay.opacity = Float(v) } } let disappeared = viewState(targetState: targetState) for (k, v) in disappeared { let isAppearingState = currentValue(for: k) let toValue = isAppearing ? isAppearingState : v let fromValue = !isAppearing ? isAppearingState : v transitionStates[k] = (fromValue, toValue) } animate(delay: targetState.delay) } } extension MotionCoreAnimationViewContext { /** Lazy loads the overlay layer. - Returns: A CALayer. */ fileprivate func getOverlayLayer() -> CALayer { if nil == overlayLayer { overlayLayer = CALayer() overlayLayer!.frame = snapshot.bounds overlayLayer!.opacity = 0 snapshot.layer.addSublayer(overlayLayer!) } return overlayLayer! } /** Retrieves the overlay key for a given key. - Parameter for key: A String. - Returns: An optional String. */ fileprivate func overlayKey(for key: String) -> String? { guard key.hasPrefix("overlay.") else { return nil } var k = key k.removeSubrange(k.startIndex..<k.index(key.startIndex, offsetBy: 8)) return k } /** Retrieves the current value for a given key. - Parameter for key: A String. - Returns: An optional Any value. */ fileprivate func currentValue(for key: String) -> Any? { if let key = overlayKey(for: key) { return overlayLayer?.value(forKeyPath: key) } if false != snapshot.layer.animationKeys()?.isEmpty { return snapshot.layer.value(forKeyPath:key) } return (snapshot.layer.presentation() ?? snapshot.layer).value(forKeyPath: key) } /** Retrieves the animation for a given key. - Parameter key: String. - Parameter beginTime: A TimeInterval. - Parameter fromValue: An optional Any value. - Parameter toValue: An optional Any value. - Parameter ignoreArc: A Boolean value to ignore an arc position. */ fileprivate func getAnimation(key: String, beginTime: TimeInterval, fromValue: Any?, toValue: Any?, ignoreArc: Bool = false) -> CAPropertyAnimation { let key = overlayKey(for: key) ?? key let anim: CAPropertyAnimation if !ignoreArc, "position" == key, let arcIntensity = targetState.arc, let fromPos = (fromValue as? NSValue)?.cgPointValue, let toPos = (toValue as? NSValue)?.cgPointValue, abs(fromPos.x - toPos.x) >= 1, abs(fromPos.y - toPos.y) >= 1 { let a = CAKeyframeAnimation(keyPath: key) let path = CGMutablePath() let maxControl = fromPos.y > toPos.y ? CGPoint(x: toPos.x, y: fromPos.y) : CGPoint(x: fromPos.x, y: toPos.y) let minControl = (toPos - fromPos) / 2 + fromPos path.move(to: fromPos) path.addQuadCurve(to: toPos, control: minControl + (maxControl - minControl) * arcIntensity) a.values = [fromValue!, toValue!] a.path = path a.duration = duration a.timingFunctions = [timingFunction] anim = a } else if #available(iOS 9.0, *), "cornerRadius" != key, let (stiffness, damping) = targetState.spring { let a = CASpringAnimation(keyPath: key) a.stiffness = stiffness a.damping = damping a.duration = a.settlingDuration * 0.9 a.fromValue = fromValue a.toValue = toValue anim = a } else { let a = CABasicAnimation(keyPath: key) a.duration = duration a.fromValue = fromValue a.toValue = toValue a.timingFunction = timingFunction anim = a } anim.fillMode = kCAFillModeBoth anim.isRemovedOnCompletion = false anim.beginTime = beginTime return anim } /** Retrieves the duration of an animation, including the duration of the animation and the initial delay. - Parameter key: A String. - Parameter beginTime: A TimeInterval. - Parameter fromValue: A optional Any value. - Parameter toValue: A optional Any value. - Returns: A TimeInterval. */ @discardableResult fileprivate func animate(key: String, beginTime: TimeInterval, fromValue: Any?, toValue: Any?) -> TimeInterval { let anim = getAnimation(key: key, beginTime:beginTime, fromValue: fromValue, toValue: toValue) if let overlayKey = overlayKey(for: key) { getOverlayLayer().add(anim, forKey: overlayKey) } else { snapshot.layer.add(anim, forKey: key) switch key { case "cornerRadius", "contentsRect", "contentsScale": contentLayer?.add(anim, forKey: key) overlayLayer?.add(anim, forKey: key) case "bounds.size": guard let fs = (fromValue as? NSValue)?.cgSizeValue else { return 0 } guard let ts = (toValue as? NSValue)?.cgSizeValue else { return 0 } // for the snapshotView(UIReplicantView): there is a // subview(UIReplicantContentView) that is hosting the real snapshot image. // because we are using CAAnimations and not UIView animations, // The snapshotView will not layout during animations. // we have to add two more animations to manually layout the content view. let fpn = NSValue(cgPoint: fs.center) let tpn = NSValue(cgPoint: ts.center) let a = getAnimation(key: "position", beginTime: 0, fromValue: fpn, toValue: tpn, ignoreArc: true) a.beginTime = anim.beginTime a.timingFunction = anim.timingFunction a.duration = anim.duration contentLayer?.add(a, forKey: "position") contentLayer?.add(anim, forKey: key) overlayLayer?.add(a, forKey: "position") overlayLayer?.add(anim, forKey: key) default: break } } return anim.duration + anim.beginTime - beginTime } /** Animates the contentLayer and overlayLayer with a given delay. - Parameter delay: A TimeInterval. */ fileprivate func animate(delay: TimeInterval) { if let v = targetState.timingFunction { timingFunction = v } if let v = targetState.duration { duration = v } let beginTime = currentTime + delay var finalDuration: TimeInterval = duration for (key, (fromValue, toValue)) in transitionStates { let neededTime = animate(key: key, beginTime: beginTime, fromValue: fromValue, toValue: toValue) finalDuration = max(finalDuration, neededTime + delay) } duration = finalDuration } /** Constructs a map of key paths to animation state values. - Parameter targetState state: A MotionTransitionState. - Returns: A map of key paths to animation values. */ fileprivate func viewState(targetState ts: MotionTransitionState) -> [String: Any?] { var ts = ts var values = [String: Any?]() if let size = ts.size { if ts.useScaleBasedSizeChange ?? targetState.useScaleBasedSizeChange ?? false { let currentSize = snapshot.bounds.size ts.append(.scale(x: size.width / currentSize.width, y: size.height / currentSize.height)) } else { values["bounds.size"] = NSValue(cgSize:size) } } if let position = ts.position { values["position"] = NSValue(cgPoint:position) } if let opacity = ts.opacity, !(snapshot is UIVisualEffectView) { values["opacity"] = NSNumber(value: opacity) } if let cornerRadius = ts.cornerRadius { values["cornerRadius"] = NSNumber(value: cornerRadius.native) } if let backgroundColor = ts.backgroundColor { values["backgroundColor"] = backgroundColor } if let zPosition = ts.zPosition { values["zPosition"] = NSNumber(value: zPosition.native) } if let borderWidth = ts.borderWidth { values["borderWidth"] = NSNumber(value: borderWidth.native) } if let borderColor = ts.borderColor { values["borderColor"] = borderColor } if let masksToBounds = ts.masksToBounds { values["masksToBounds"] = masksToBounds } if ts.displayShadow { if let shadowColor = ts.shadowColor { values["shadowColor"] = shadowColor } if let shadowRadius = ts.shadowRadius { values["shadowRadius"] = NSNumber(value: shadowRadius.native) } if let shadowOpacity = ts.shadowOpacity { values["shadowOpacity"] = NSNumber(value: shadowOpacity) } if let shadowPath = ts.shadowPath { values["shadowPath"] = shadowPath } if let shadowOffset = ts.shadowOffset { values["shadowOffset"] = NSValue(cgSize: shadowOffset) } } if let contentsRect = ts.contentsRect { values["contentsRect"] = NSValue(cgRect: contentsRect) } if let contentsScale = ts.contentsScale { values["contentsScale"] = NSNumber(value: contentsScale.native) } if let transform = ts.transform { values["transform"] = NSValue(caTransform3D: transform) } if let (color, opacity) = ts.overlay { values["overlay.backgroundColor"] = color values["overlay.opacity"] = NSNumber(value: opacity.native) } return values } /** Moves a layer's animation to a given elapsed time. - Parameter layer: A CALayer. - Parameter elapsedTime: A TimeInterval. */ fileprivate func seek(layer: CALayer, elapsedTime: TimeInterval) { let timeOffset = elapsedTime - targetState.delay for (key, anim) in layer.animations { anim.speed = 0 anim.timeOffset = max(0, min(anim.duration - 0.01, timeOffset)) layer.removeAnimation(forKey: key) layer.add(anim, forKey: key) } } }
3a035c895e3cd5616f2112331a67a150
35.679157
153
0.56736
false
false
false
false
wikimedia/wikipedia-ios
refs/heads/main
WMF Framework/ArticleCacheController.swift
mit
1
import Foundation public final class ArticleCacheController: CacheController { init(moc: NSManagedObjectContext, imageCacheController: ImageCacheController, session: Session, configuration: Configuration, preferredLanguageDelegate: WMFPreferredLanguageInfoProvider) { let articleFetcher = ArticleFetcher(session: session, configuration: configuration) let imageInfoFetcher = MWKImageInfoFetcher(session: session, configuration: configuration) imageInfoFetcher.preferredLanguageDelegate = preferredLanguageDelegate let cacheFileWriter = CacheFileWriter(fetcher: articleFetcher) let articleDBWriter = ArticleCacheDBWriter(articleFetcher: articleFetcher, cacheBackgroundContext: moc, imageController: imageCacheController, imageInfoFetcher: imageInfoFetcher) super.init(dbWriter: articleDBWriter, fileWriter: cacheFileWriter) } enum ArticleCacheControllerError: Error { case invalidDBWriterType } // syncs already cached resources with mobile-html-offline-resources and media-list endpoints (caches new urls, removes old urls) public func syncCachedResources(url: URL, groupKey: CacheController.GroupKey, groupCompletion: @escaping GroupCompletionBlock) { guard let articleDBWriter = dbWriter as? ArticleCacheDBWriter else { groupCompletion(.failure(error: ArticleCacheControllerError.invalidDBWriterType)) return } articleDBWriter.syncResources(url: url, groupKey: groupKey) { (result) in switch result { case .success(let syncResult): let group = DispatchGroup() var successfulAddKeys: [CacheController.UniqueKey] = [] var failedAddKeys: [(CacheController.UniqueKey, Error)] = [] var successfulRemoveKeys: [CacheController.UniqueKey] = [] var failedRemoveKeys: [(CacheController.UniqueKey, Error)] = [] // add new urls in file system for urlRequest in syncResult.addURLRequests { guard let uniqueKey = self.fileWriter.uniqueFileNameForURLRequest(urlRequest), urlRequest.url != nil else { continue } group.enter() self.fileWriter.add(groupKey: groupKey, urlRequest: urlRequest) { (fileWriterResult) in switch fileWriterResult { case .success(let response, _): self.dbWriter.markDownloaded(urlRequest: urlRequest, response: response) { (dbWriterResult) in defer { group.leave() } switch dbWriterResult { case .success: successfulAddKeys.append(uniqueKey) case .failure(let error): failedAddKeys.append((uniqueKey, error)) } } case .failure(let error): defer { group.leave() } failedAddKeys.append((uniqueKey, error)) } } } // remove old urls in file system for key in syncResult.removeItemKeyAndVariants { guard let uniqueKey = self.fileWriter.uniqueFileNameForItemKey(key.itemKey, variant: key.variant) else { continue } group.enter() self.fileWriter.remove(itemKey: key.itemKey, variant: key.variant) { (fileWriterResult) in switch fileWriterResult { case .success: self.dbWriter.remove(itemAndVariantKey: key) { (dbWriterResult) in defer { group.leave() } switch dbWriterResult { case .success: successfulRemoveKeys.append(uniqueKey) case .failure(let error): failedRemoveKeys.append((uniqueKey, error)) } } case .failure(let error): defer { group.leave() } failedRemoveKeys.append((uniqueKey, error)) } } } group.notify(queue: DispatchQueue.global(qos: .userInitiated)) { if let error = failedAddKeys.first?.1 ?? failedRemoveKeys.first?.1 { groupCompletion(.failure(error: CacheControllerError.atLeastOneItemFailedInSync(error))) return } let successKeys = successfulAddKeys + successfulRemoveKeys groupCompletion(.success(uniqueKeys: successKeys)) } case .failure(let error): groupCompletion(.failure(error: error)) } } } public func cacheFromMigration(desktopArticleURL: URL, content: String, completionHandler: @escaping ((Error?) -> Void)) { // articleURL should be desktopURL guard let articleDBWriter = dbWriter as? ArticleCacheDBWriter else { completionHandler(ArticleCacheControllerError.invalidDBWriterType) return } cacheBundledResourcesIfNeeded(desktopArticleURL: desktopArticleURL) { (cacheBundledError) in articleDBWriter.addMobileHtmlURLForMigration(desktopArticleURL: desktopArticleURL, success: { urlRequest in self.fileWriter.addMobileHtmlContentForMigration(content: content, urlRequest: urlRequest, success: { articleDBWriter.markDownloaded(urlRequest: urlRequest, response: nil) { (result) in switch result { case .success: if cacheBundledError == nil { completionHandler(nil) } else { completionHandler(cacheBundledError) } case .failure(let error): completionHandler(error) } } }) { (error) in completionHandler(error) } }) { (error) in completionHandler(error) } } } private func bundledResourcesAreCached() -> Bool { guard let articleDBWriter = dbWriter as? ArticleCacheDBWriter else { return false } return articleDBWriter.bundledResourcesAreCached() } private func cacheBundledResourcesIfNeeded(desktopArticleURL: URL, completionHandler: @escaping ((Error?) -> Void)) { // articleURL should be desktopURL guard let articleDBWriter = dbWriter as? ArticleCacheDBWriter else { completionHandler(ArticleCacheControllerError.invalidDBWriterType) return } if !articleDBWriter.bundledResourcesAreCached() { articleDBWriter.addBundledResourcesForMigration(desktopArticleURL: desktopArticleURL) { (result) in switch result { case .success(let requests): self.fileWriter.addBundledResourcesForMigration(urlRequests: requests, success: { (_) in let bulkRequests = requests.map { ArticleCacheDBWriter.BulkMarkDownloadRequest(urlRequest: $0, response: nil) } articleDBWriter.markDownloaded(requests: bulkRequests) { (result) in switch result { case .success: completionHandler(nil) case .failure(let error): completionHandler(error) } } }) { (error) in completionHandler(error) } case .failure(let error): completionHandler(error) } } } else { completionHandler(nil) } } }
46054b3dd6d850aaef93470c5b535b4f
44.644231
192
0.484517
false
false
false
false
hirohisa/RxSwift
refs/heads/master
RxExample/RxExample/Examples/Dependencies.swift
mit
3
// // Dependencies.swift // WikipediaImageSearch // // Created by carlos on 13/5/15. // Copyright (c) 2015 Carlos García. All rights reserved. // import Foundation #if !RX_NO_MODULE import RxSwift #endif class Dependencies { static let sharedDependencies = Dependencies() // Singleton let URLSession = NSURLSession.sharedSession() let backgroundWorkScheduler: ImmediateScheduler let mainScheduler: SerialDispatchQueueScheduler let wireframe: Wireframe private init() { wireframe = DefaultWireframe() let operationQueue = NSOperationQueue() operationQueue.maxConcurrentOperationCount = 2 if operationQueue.respondsToSelector("qualityOfService") { operationQueue.qualityOfService = NSQualityOfService.UserInitiated } backgroundWorkScheduler = OperationQueueScheduler(operationQueue: operationQueue) mainScheduler = MainScheduler.sharedInstance } }
cfddc1834e11bcdd24772b72631d074b
26.388889
89
0.705882
false
false
false
false
BlessNeo/ios-charts
refs/heads/master
Charts/Classes/Charts/PieChartView.swift
apache-2.0
44
// // PieChartView.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import UIKit /// View that represents a pie chart. Draws cake like slices. public class PieChartView: PieRadarChartViewBase { /// rect object that represents the bounds of the piechart, needed for drawing the circle private var _circleBox = CGRect() /// array that holds the width of each pie-slice in degrees private var _drawAngles = [CGFloat]() /// array that holds the absolute angle in degrees of each slice private var _absoluteAngles = [CGFloat]() public override init(frame: CGRect) { super.init(frame: frame) } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } internal override func initialize() { super.initialize() renderer = PieChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler) } public override func drawRect(rect: CGRect) { super.drawRect(rect) if (_dataNotSet) { return } let context = UIGraphicsGetCurrentContext() renderer!.drawData(context: context) if (valuesToHighlight()) { renderer!.drawHighlighted(context: context, indices: _indicesToHightlight) } renderer!.drawExtras(context: context) renderer!.drawValues(context: context) _legendRenderer.renderLegend(context: context) drawDescription(context: context) } internal override func calculateOffsets() { super.calculateOffsets() // prevent nullpointer when no data set if (_dataNotSet) { return } var radius = diameter / 2.0 var c = centerOffsets // create the circle box that will contain the pie-chart (the bounds of the pie-chart) _circleBox.origin.x = c.x - radius _circleBox.origin.y = c.y - radius _circleBox.size.width = radius * 2.0 _circleBox.size.height = radius * 2.0 } internal override func calcMinMax() { super.calcMinMax() calcAngles() } public override func getMarkerPosition(#entry: ChartDataEntry, highlight: ChartHighlight) -> CGPoint { /// PieChart does not support MarkerView return CGPoint(x: 0.0, y: 0.0) } /// calculates the needed angles for the chart slices private func calcAngles() { _drawAngles = [CGFloat]() _absoluteAngles = [CGFloat]() _drawAngles.reserveCapacity(_data.yValCount) _absoluteAngles.reserveCapacity(_data.yValCount) var dataSets = _data.dataSets var cnt = 0 for (var i = 0; i < _data.dataSetCount; i++) { var set = dataSets[i] var entries = set.yVals for (var j = 0; j < entries.count; j++) { _drawAngles.append(calcAngle(abs(entries[j].value))) if (cnt == 0) { _absoluteAngles.append(_drawAngles[cnt]) } else { _absoluteAngles.append(_absoluteAngles[cnt - 1] + _drawAngles[cnt]) } cnt++ } } } /// checks if the given index in the given DataSet is set for highlighting or not public func needsHighlight(#xIndex: Int, dataSetIndex: Int) -> Bool { // no highlight if (!valuesToHighlight() || dataSetIndex < 0) { return false } for (var i = 0; i < _indicesToHightlight.count; i++) { // check if the xvalue for the given dataset needs highlight if (_indicesToHightlight[i].xIndex == xIndex && _indicesToHightlight[i].dataSetIndex == dataSetIndex) { return true } } return false } /// calculates the needed angle for a given value private func calcAngle(value: Double) -> CGFloat { return CGFloat(value) / CGFloat(_data.yValueSum) * 360.0 } public override func indexForAngle(angle: CGFloat) -> Int { // take the current angle of the chart into consideration var a = ChartUtils.normalizedAngleFromAngle(angle - self.rotationAngle) for (var i = 0; i < _absoluteAngles.count; i++) { if (_absoluteAngles[i] > a) { return i } } return -1; // return -1 if no index found } /// Returns the index of the DataSet this x-index belongs to. public func dataSetIndexForIndex(xIndex: Int) -> Int { var dataSets = _data.dataSets for (var i = 0; i < dataSets.count; i++) { if (dataSets[i].entryForXIndex(xIndex) !== nil) { return i } } return -1 } /// returns an integer array of all the different angles the chart slices /// have the angles in the returned array determine how much space (of 360°) /// each slice takes public var drawAngles: [CGFloat] { return _drawAngles } /// returns the absolute angles of the different chart slices (where the /// slices end) public var absoluteAngles: [CGFloat] { return _absoluteAngles } /// Sets the color for the hole that is drawn in the center of the PieChart (if enabled). /// NOTE: Use holeTransparent with holeColor = nil to make the hole transparent. public var holeColor: UIColor? { get { return (renderer as! PieChartRenderer).holeColor! } set { (renderer as! PieChartRenderer).holeColor = newValue setNeedsDisplay() } } /// Set the hole in the center of the PieChart transparent public var holeTransparent: Bool { get { return (renderer as! PieChartRenderer).holeTransparent } set { (renderer as! PieChartRenderer).holeTransparent = newValue setNeedsDisplay() } } /// Returns true if the hole in the center of the PieChart is transparent, false if not. public var isHoleTransparent: Bool { return (renderer as! PieChartRenderer).holeTransparent } /// true if the hole in the center of the pie-chart is set to be visible, false if not public var drawHoleEnabled: Bool { get { return (renderer as! PieChartRenderer).drawHoleEnabled } set { (renderer as! PieChartRenderer).drawHoleEnabled = newValue setNeedsDisplay() } } /// :returns: true if the hole in the center of the pie-chart is set to be visible, false if not public var isDrawHoleEnabled: Bool { get { return (renderer as! PieChartRenderer).drawHoleEnabled } } /// the text that is displayed in the center of the pie-chart. By default, the text is "Total value + sum of all values" public var centerText: String! { get { return (renderer as! PieChartRenderer).centerText } set { (renderer as! PieChartRenderer).centerText = newValue setNeedsDisplay() } } /// true if drawing the center text is enabled public var drawCenterTextEnabled: Bool { get { return (renderer as! PieChartRenderer).drawCenterTextEnabled } set { (renderer as! PieChartRenderer).drawCenterTextEnabled = newValue setNeedsDisplay() } } /// :returns: true if drawing the center text is enabled public var isDrawCenterTextEnabled: Bool { get { return (renderer as! PieChartRenderer).drawCenterTextEnabled } } internal override var requiredBottomOffset: CGFloat { return _legend.font.pointSize * 2.0 } internal override var requiredBaseOffset: CGFloat { return 0.0 } public override var radius: CGFloat { return _circleBox.width / 2.0 } /// returns the circlebox, the boundingbox of the pie-chart slices public var circleBox: CGRect { return _circleBox } /// returns the center of the circlebox public var centerCircleBox: CGPoint { return CGPoint(x: _circleBox.midX, y: _circleBox.midY) } /// Sets the font of the center text of the piechart. public var centerTextFont: UIFont { get { return (renderer as! PieChartRenderer).centerTextFont } set { (renderer as! PieChartRenderer).centerTextFont = newValue setNeedsDisplay() } } /// Sets the color of the center text of the piechart. public var centerTextColor: UIColor { get { return (renderer as! PieChartRenderer).centerTextColor } set { (renderer as! PieChartRenderer).centerTextColor = newValue setNeedsDisplay() } } /// the radius of the hole in the center of the piechart in percent of the maximum radius (max = the radius of the whole chart) /// :default: 0.5 (50%) (half the pie) public var holeRadiusPercent: CGFloat { get { return (renderer as! PieChartRenderer).holeRadiusPercent } set { (renderer as! PieChartRenderer).holeRadiusPercent = newValue setNeedsDisplay() } } /// the radius of the transparent circle that is drawn next to the hole in the piechart in percent of the maximum radius (max = the radius of the whole chart) /// :default: 0.55 (55%) -> means 5% larger than the center-hole by default public var transparentCircleRadiusPercent: CGFloat { get { return (renderer as! PieChartRenderer).transparentCircleRadiusPercent } set { (renderer as! PieChartRenderer).transparentCircleRadiusPercent = newValue setNeedsDisplay() } } /// set this to true to draw the x-value text into the pie slices public var drawSliceTextEnabled: Bool { get { return (renderer as! PieChartRenderer).drawXLabelsEnabled } set { (renderer as! PieChartRenderer).drawXLabelsEnabled = newValue setNeedsDisplay() } } /// :returns: true if drawing x-values is enabled, false if not public var isDrawSliceTextEnabled: Bool { get { return (renderer as! PieChartRenderer).drawXLabelsEnabled } } /// If this is enabled, values inside the PieChart are drawn in percent and not with their original value. Values provided for the ValueFormatter to format are then provided in percent. public var usePercentValuesEnabled: Bool { get { return (renderer as! PieChartRenderer).usePercentValuesEnabled } set { (renderer as! PieChartRenderer).usePercentValuesEnabled = newValue setNeedsDisplay() } } /// :returns: true if drawing x-values is enabled, false if not public var isUsePercentValuesEnabled: Bool { get { return (renderer as! PieChartRenderer).usePercentValuesEnabled } } /// the line break mode for center text. /// note that different line break modes give different performance results - Clipping being the fastest, WordWrapping being the slowst. public var centerTextLineBreakMode: NSLineBreakMode { get { return (renderer as! PieChartRenderer).centerTextLineBreakMode } set { (renderer as! PieChartRenderer).centerTextLineBreakMode = newValue setNeedsDisplay() } } /// the rectangular radius of the bounding box for the center text, as a percentage of the pie hole public var centerTextRadiusPercent: CGFloat { get { return (renderer as! PieChartRenderer).centerTextRadiusPercent } set { (renderer as! PieChartRenderer).centerTextRadiusPercent = newValue setNeedsDisplay() } } }
9a090ec29ebc2dafb25226b456981bd0
26.741525
189
0.57145
false
false
false
false
zsheikh-systango/WordPower
refs/heads/master
Skeleton/Skeleton/AppDelegate.swift
mit
1
// // AppDelegate.swift // WordPower // // Created by BestPeers on 31/05/17. // Copyright © 2017 BestPeers. All rights reserved. // import UIKit import CoreData import SMobiLog import Reachability @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var isNetworkAvailable: Bool = true let reachability = Reachability()! func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. setupNetworkMonitoring() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var persistentContainer: NSPersistentContainer = { /* The persistent container for the application. This implementation creates and returns a container, having loaded the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. */ let container = NSPersistentContainer(name: "Skeleton") container.loadPersistentStores(completionHandler: { (storeDescription, error) in if let error = error as NSError? { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. /* Typical reasons for an error here include: * The parent directory does not exist, cannot be created, or disallows writing. * The persistent store is not accessible, due to permissions or data protection when the device is locked. * The device is out of space. * The store could not be migrated to the current model version. Check the error message to determine what the actual problem was. */ fatalError("Unresolved error \(error), \(error.userInfo)") } }) return container }() // MARK: - Core Data Saving support func saveContext () { let context = persistentContainer.viewContext if context.hasChanges { do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. let nserror = error as NSError fatalError("Unresolved error \(nserror), \(nserror.userInfo)") } } } public func isNetworkReachable() -> Bool { return self.isNetworkAvailable } func setupNetworkMonitoring() { reachability.whenReachable = { reachability in // this is called on a background thread, but UI updates must // be on the main thread, like this: DispatchQueue.main.async { if reachability.connection == .wifi { print("Reachable via WiFi") } else { print("Reachable via Cellular") } self.isNetworkAvailable = true } } reachability.whenUnreachable = { reachability in // this is called on a background thread, but UI updates must // be on the main thread, like this: DispatchQueue.main.async { print("Not reachable") self.isNetworkAvailable = false } } NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged),name: Notification.Name.reachabilityChanged,object: reachability) do { try reachability.startNotifier() } catch { print("Unable to start notifier") } } @objc func reachabilityChanged(note: Notification) { let reachability = note.object as! Reachability if reachability.connection != .none { if reachability.connection == .wifi { print("Reachable via WiFi") } else { print("Reachable via Cellular") } self.isNetworkAvailable = true } else { print("Network not reachable") self.isNetworkAvailable = false } } }
e86f8f3b0d4ebb4202e2285dd6248246
41.675325
285
0.642879
false
false
false
false
neoneye/SwiftyFORM
refs/heads/master
Source/Form/ToggleExpandCollapse.swift
mit
1
// MIT license. Copyright (c) 2021 SwiftyFORM. All rights reserved. import UIKit public protocol ExpandedCell { var toggleCell: UITableViewCell? { get } // `false` when its behavior is AlwaysExpanded, in this case we don't want it collapsed var isCollapsable: Bool { get } } public struct ToggleExpandCollapse { public static func execute(toggleCell: UITableViewCell, expandedCell: UITableViewCell, tableView: UITableView, sectionArray: TableViewSectionArray) { //SwiftyFormLog("will expand collapse") // If the expanded cell already is visible then collapse it let whatToCollapse = WhatToCollapse.process( toggleCell: toggleCell, expandedCell: expandedCell, sectionArray: sectionArray ) //print("whatToCollapse: \(whatToCollapse)") if !whatToCollapse.indexPaths.isEmpty { for cell in whatToCollapse.toggleCells { if let cell2 = cell as? AssignAppearance { cell2.assignDefaultColors() } } tableView.beginUpdates() tableView.deleteRows(at: whatToCollapse.indexPaths, with: .fade) tableView.endUpdates() } // If the expanded cell is hidden then expand it let whatToExpand = WhatToExpand.process( expandedCell: expandedCell, sectionArray: sectionArray, isCollapse: whatToCollapse.isCollapse ) //print("whatToExpand: \(whatToExpand)") if !whatToExpand.indexPaths.isEmpty { var toggleIndexPath: IndexPath? if let item = sectionArray.findItem(toggleCell) { toggleIndexPath = sectionArray.indexPathForItem(item) } if let cell = toggleCell as? AssignAppearance { cell.assignTintColors() } CATransaction.begin() CATransaction.setCompletionBlock({ // Ensure that the toggleCell and expandedCell are visible if let indexPath = toggleIndexPath { //print("scroll to visible: \(indexPath)") tableView.form_scrollToVisibleAfterExpand(indexPath) } }) tableView.beginUpdates() tableView.insertRows(at: whatToExpand.indexPaths, with: .fade) tableView.endUpdates() CATransaction.commit() } //SwiftyFormLog("did expand collapse") } } struct WhatToCollapse { let indexPaths: [IndexPath] let toggleCells: [UITableViewCell] let isCollapse: Bool /// If the expanded cell already is visible then collapse it static func process(toggleCell: UITableViewCell, expandedCell: UITableViewCell, sectionArray: TableViewSectionArray) -> WhatToCollapse { //debugPrint(sectionArray) var indexPaths = [IndexPath]() var toggleCells = [UITableViewCell]() var isCollapse = false for (sectionIndex, section) in sectionArray.sections.enumerated() { for (row, item) in section.cells.visibleItems.enumerated() { //let cellType = type(of: item.cell) //print("\(sectionIndex) \(row) \(cellType)") if item.cell === expandedCell { //print("\(sectionIndex) \(row) this is the expanded cell to be collapsed") item.hidden = true indexPaths.append(IndexPath(row: row, section: sectionIndex)) toggleCells.append(toggleCell) isCollapse = true continue } if let expandedCell2 = item.cell as? ExpandedCell, expandedCell2.isCollapsable { if let toggleCell2 = expandedCell2.toggleCell { //print("\(sectionIndex) \(row) this is a toggle cell to be collapsed") item.hidden = true indexPaths.append(IndexPath(row: row, section: sectionIndex)) toggleCells.append(toggleCell2) } } } } if !indexPaths.isEmpty { //let count0 = sectionArray.numberOfVisibleItems sectionArray.reloadVisibleItems() //let count1 = sectionArray.numberOfVisibleItems //print("reloaded visible items \(count0) -> \(count1)") //debugPrint(sectionArray) } return WhatToCollapse(indexPaths: indexPaths, toggleCells: toggleCells, isCollapse: isCollapse) } } struct WhatToExpand { let indexPaths: [IndexPath] /// If the expanded cell is hidden then expand it static func process(expandedCell: UITableViewCell, sectionArray: TableViewSectionArray, isCollapse: Bool) -> WhatToExpand { if isCollapse { return WhatToExpand(indexPaths: []) } guard let item = sectionArray.findItem(expandedCell) else { return WhatToExpand(indexPaths: []) } if !item.hidden { return WhatToExpand(indexPaths: []) } // The expanded cell is hidden. Make it visible item.hidden = false sectionArray.reloadVisibleItems() guard let indexPath = sectionArray.indexPathForItem(item) else { print("ERROR: Expected indexPath, but got nil. At this point the item is supposed to be visible") return WhatToExpand(indexPaths: []) } return WhatToExpand(indexPaths: [indexPath]) } }
e181bf235875944c16f1cf7440835604
29.276316
150
0.725989
false
false
false
false
dkarsh/SwiftGoal
refs/heads/master
Carthage/Checkouts/Argo/ArgoTests/Tests/PListDecodingTests.swift
mit
4
import XCTest import Argo class PListDecodingTests: XCTestCase { func testDecodingAllTypesFromPList() { let model: TestModel? = PListFileReader.plist(fromFile: "types").flatMap(decode) XCTAssert(model != nil) XCTAssert(model?.numerics.int == 5) XCTAssert(model?.numerics.int64 == 9007199254740992) XCTAssert(model?.numerics.uint == 500) XCTAssert(model?.numerics.uint64 == 9223372036854775807) XCTAssert(model?.numerics.uint64String == 18446744073709551614) XCTAssert(model?.numerics.double == 3.4) XCTAssert(model?.numerics.float == 1.1) XCTAssert(model?.numerics.intOpt == nil) XCTAssert(model?.string == "Cooler User") XCTAssert(model?.bool == false) XCTAssert(model?.stringArray.count == 2) XCTAssert(model?.stringArrayOpt == nil) XCTAssert(model?.eStringArray.count == 2) XCTAssert(model?.eStringArrayOpt != nil) XCTAssert(model?.eStringArrayOpt?.count == 0) XCTAssert(model?.userOpt != nil) XCTAssert(model?.userOpt?.id == 6) XCTAssert(model?.dict ?? [:] == ["foo": "bar"]) } }
1ddfe2c7f68522a0af51add0fbc7583c
37.214286
84
0.694393
false
true
false
false
aquarchitect/MyKit
refs/heads/master
Sources/Shared/Utilities/Matrix.swift
mit
1
// // Matrix.swift // MyKit // // Created by Hai Nguyen. // Copyright (c) 2015 Hai Nguyen. // /// Simple _Matrix_ to work with LCS algorithm (debugging purposes only). /// /// - warning: reference [Surge](https://github.com/mattt/Surge) for optimized matrix computation. public struct Matrix<Element> { // MARK: Property fileprivate var elements: [Element] public let rows: Int public let columns: Int public var count: Int { return elements.count } // MARK: Initialization public init(repeating value: Element, rows: Int, columns: Int) { self.rows = rows self.columns = columns self.elements = Array(repeating: value, count: rows * columns) } } // MARK: - Support Methods private extension Matrix { func isValid(row: Int, column: Int) -> Bool { return (0..<rows).contains(row) && (0..<columns).contains(column) } } // MARK: - Supscription public extension Matrix { subscript(row: Int, column: Int) -> Element { get { assert(isValid(row: row, column: column), "Index out of bounds.") return elements[row * columns + column] } set { assert(isValid(row: row, column: column), "Index out of bounds") elements[row * columns + column] = newValue } } subscript(row row: Int) -> ArraySlice<Element> { get { assert(row < rows, "Row out of bounds.") let startIndex = row * columns let endIndex = startIndex + columns return elements[startIndex..<endIndex] } set { assert(row < rows, "Row out of bounds.") assert(newValue.count == columns, "Column out of bounds") let startIndex = row * columns let endIndex = startIndex + columns elements.replaceSubrange(startIndex..<endIndex, with: newValue) } } subscript(column column: Int) -> ArraySlice<Element> { get { assert(column < columns, "Column out of bounds") let base = (0..<rows) .makeIterator() .lazy .map({ self.elements[$0 * self.columns + column] }) return ArraySlice(base) } set { assert(column < columns, "Column out of bounds") assert(newValue.count == rows, "Row out of bounds") for index in 0..<rows { elements[index * columns + column] = newValue[index] } } } } // MARK: - Custom String extension Matrix: CustomDebugStringConvertible { public var debugDescription: String { let displayRow: (Int) -> String = { row in (0..<self.columns) .map { column in "\(self[row, column])" } .joined(separator: " ") } return (0..<rows) .map(displayRow) .joined(separator: "\n") } }
81a0c8f00e81b00e7ed7b0afd885eb59
25.366071
98
0.553336
false
false
false
false
alvivi/BadType
refs/heads/master
BadType/FontStyle.swift
bsd-3-clause
1
// Copyright 2015 Alvaro Vilanova Vidal. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. import UIKit private let styleNameKey = "Style Name" private let sizeCategoriesKey = "Size Categories" private let categoryAttributeSizeKey = "Size" private let categoryAttributeTraitsKey = "Traits" private let categoryAttributeFontNameKey = "Font Name" // MARK: - FontStyle Struct internal struct FontStyle { let name: String let sizes: [CGFloat] let traits: [UIFontDescriptorSymbolicTraits] let fontNames: [String?] init(fromDictionary dictionary: Dictionary<String, AnyObject>) throws { guard let name = dictionary[styleNameKey] as? String else { throw Error.InvalidStyle("cannot read style name") } self.name = name guard let sizesCategories = dictionary[sizeCategoriesKey] as? Dictionary<String, AnyObject> else { throw Error.InvalidStyle("cannot read size categories") } var sizes = Array<CGFloat>(count: 12, repeatedValue: 14) var traits = Array<UIFontDescriptorSymbolicTraits>(count: 12, repeatedValue: []) var fontNames = Array<String?>(count: 12, repeatedValue: nil) for (categoryName, category) in sizesCategories { guard let index = getCategoryNameIndex(categoryName) else { throw Error.InvalidStyle("invalid size category name \"\(categoryName)\"") } guard let size = category[categoryAttributeSizeKey] as? NSNumber else { throw Error.InvalidStyle("invalid size category \"\(categoryName)\" value") } if size.floatValue < 0 { throw Error.InvalidStyle("invalid negative size value") } sizes[index] = CGFloat(size.doubleValue) if let object = category[categoryAttributeTraitsKey] as? NSObject { traits[index] = try UIFontDescriptorSymbolicTraits.tratisFromObject(object) } if let fontNameString = category[categoryAttributeFontNameKey] as? String { fontNames[index] = fontNameString } } self.sizes = sizes self.traits = traits self.fontNames = fontNames } } // MARK: - UIFontDescriptorSymbolicTraits Extension private extension UIFontDescriptorSymbolicTraits { private static func tratisFromObject(object: NSObject) throws -> UIFontDescriptorSymbolicTraits { if let traitString = object as? String { return try traitsFromString(traitString) } if let traitsArray = object as? [NSObject] { return try traitsFromArray(traitsArray) } return [] } private static func traitsFromArray(array: [NSObject]) throws -> UIFontDescriptorSymbolicTraits { var traits: UIFontDescriptorSymbolicTraits = [] for object in array { guard let traitString = object as? String else { continue } traits.unionInPlace(try traitsFromString(traitString) ) } return traits } // swiftlint:disable function_body_length private static func traitsFromString(traitString: String) throws -> UIFontDescriptorSymbolicTraits { switch traitString { case "Italic": return .TraitItalic case "Bold": return .TraitBold case "Expanded": return .TraitExpanded case "Condensed": return .TraitCondensed case "MonoSpace": return .TraitMonoSpace case "Vertical": return .TraitVertical case "UIOptimized": return .TraitUIOptimized case "TightLeading": return .TraitTightLeading case "LooseLeading": return .TraitLooseLeading case "Mask": return .ClassMask case "Unknown": return .ClassUnknown case "OldStyleSerifs": return .ClassOldStyleSerifs case "TransitionalSerifs": return .ClassTransitionalSerifs case "ModernSerifs": return .ClassModernSerifs case "ClarendonSerifs": return .ClassClarendonSerifs case "SlabSerifs": return .ClassSlabSerifs case "FreeformSerifs": return .ClassFreeformSerifs case "SansSerif": return .ClassSansSerif case "Ornamentals": return .ClassOrnamentals case "Scripts": return .ClassScripts case "Symbolic": return .ClassSymbolic default: throw Error.InvalidStyle("trait \"\(traitString)\" is invalid") } } // swiftlint:enable function_body_length } private func getCategoryNameIndex(name: String) -> Int? { switch name { case "ExtraSmall": return 0 case "Small": return 1 case "Medium": return 2 case "Large": return 3 case "ExtraLarge": return 4 case "ExtraExtraLarge": return 5 case "ExtraExtraExtraLarge": return 6 case "AccessibilityMedium": return 7 case "AccessibilityLarge": return 8 case "AccessibilityExtraLarge": return 9 case "AccessibilityExtraExtraLarge": return 10 case "AccessibilityExtraExtraExtraLarge": return 11 default: return nil } }
8f739167c384872182f73cccb6b2d4c3
29.08589
102
0.698002
false
false
false
false
CosmicMind/Samples
refs/heads/development
Projects/Programmatic/Layer/Layer/ViewController.swift
bsd-3-clause
1
/* * Copyright (C) 2015 - 2018, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit import Material class ViewController: UIViewController { fileprivate var layer: Layer! @IBOutlet weak var bottomBar: Bar! override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .white prepareLayer() } } extension ViewController { fileprivate func prepareLayer() { let w = view.frame.width let h = view.frame.height let d: CGFloat = 100 layer = Layer(frame: CGRect(x: (w - d) / 2, y: (h - d) / 2, width: d, height: d)) layer.depthPreset = .depth3 layer.shapePreset = .circle layer.backgroundColor = Color.white.cgColor layer.image = UIImage(named: "CosmicMind") view.layer.addSublayer(layer) } }
3a3174c939c540631fcc77e74d4c9e30
38.229508
89
0.712495
false
false
false
false
jhend11/Coinvert
refs/heads/master
Coinvert/Coinvert/MenuTransitionManager2.swift
lgpl-3.0
1
// // MenuTransitionManager.swift // Menu // // Created by Mathew Sanders on 9/7/14. // Copyright (c) 2014 Mat. All rights reserved. // import UIKit class MenuTransitionManager2: NSObject, UIViewControllerAnimatedTransitioning, UIViewControllerTransitioningDelegate { private var presenting = false // MARK: UIViewControllerAnimatedTransitioning protocol methods // animate a change from one viewcontroller to another func animateTransition(transitionContext: UIViewControllerContextTransitioning) { // get reference to our fromView, toView and the container view that we should perform the transition in let container = transitionContext.containerView() // create a tuple of our screens let screens : (from:UIViewController, to:UIViewController) = (transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey)!, transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey)!) // assign references to our menu view controller and the 'bottom' view controller from the tuple // remember that our menuViewController will alternate between the from and to view controller depending if we're presenting or dismissing let menuViewController2 = !self.presenting ? screens.from as MenuViewController2 : screens.to as MenuViewController2 let bottomViewController = !self.presenting ? screens.to as UIViewController : screens.from as UIViewController let menuView = menuViewController2.view let bottomView = bottomViewController.view // prepare menu items to slide in if (self.presenting){ self.offStageMenuController(menuViewController2) } // add the both views to our view controller container.addSubview(bottomView) container.addSubview(menuView) let duration = self.transitionDuration(transitionContext) // perform the animation! UIView.animateWithDuration(duration, delay: 0.0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.8, options: nil, animations: { if (self.presenting){ self.onStageMenuController(menuViewController2) // onstage items: slide in } else { self.offStageMenuController(menuViewController2) // offstage items: slide out } }, completion: { finished in // tell our transitionContext object that we've finished animating transitionContext.completeTransition(true) // bug: we have to manually add our 'to view' back http://openradar.appspot.com/radar?id=5320103646199808 UIApplication.sharedApplication().keyWindow!.addSubview(screens.to.view) }) } func offStage(amount: CGFloat) -> CGAffineTransform { return CGAffineTransformMakeTranslation(amount, 0) } func offStageMenuController(menuViewController: MenuViewController2){ menuViewController.view.alpha = 0 // setup paramaters for 2D transitions for animations let topRowOffset :CGFloat = 111 let middle1RowOffset :CGFloat = 223 let middle2RowOffset :CGFloat = 334 let bottomRowOffset :CGFloat = 446 menuViewController.bitcoinIcon2.transform = self.offStage(bottomRowOffset) menuViewController.bitcoinLabel2.transform = self.offStage(bottomRowOffset) menuViewController.litecoinIcon2.transform = self.offStage(bottomRowOffset) menuViewController.litecoinLabel2.transform = self.offStage(bottomRowOffset) menuViewController.dogecoinIcon2.transform = self.offStage(middle2RowOffset) menuViewController.dogecoinLabel2.transform = self.offStage(middle2RowOffset) // menuViewController.darcoinIcon2.transform = self.offStage(-middle2RowOffset) // menuViewController.darkcoinLabel2.transform = self.offStage(-middle2RowOffset) // // menuViewController.feathercoinIcon2.transform = self.offStage(-middle1RowOffset) // menuViewController.feathercoinLabel2.transform = self.offStage(-middle1RowOffset) // // menuViewController.namecoinIcon2.transform = self.offStage(middle1RowOffset) // menuViewController.namecoinLabel2.transform = self.offStage(middle1RowOffset) // // menuViewController.peercoinIcon2.transform = self.offStage(-topRowOffset) // menuViewController.peercoinLabel2.transform = self.offStage(-topRowOffset) // // menuViewController.blackcoinIcon2.transform = self.offStage(topRowOffset) // menuViewController.blackcoinLabel2.transform = self.offStage(topRowOffset) } func onStageMenuController(menuViewController: MenuViewController2){ // prepare menu to fade in menuViewController.view.alpha = 1 menuViewController.bitcoinIcon2.transform = CGAffineTransformIdentity menuViewController.bitcoinLabel2.transform = CGAffineTransformIdentity menuViewController.litecoinIcon2.transform = CGAffineTransformIdentity menuViewController.litecoinLabel2.transform = CGAffineTransformIdentity menuViewController.dogecoinIcon2.transform = CGAffineTransformIdentity menuViewController.dogecoinLabel2.transform = CGAffineTransformIdentity // menuViewController.darcoinIcon2.transform = CGAffineTransformIdentity // menuViewController.darkcoinLabel2.transform = CGAffineTransformIdentity // // menuViewController.feathercoinIcon2.transform = CGAffineTransformIdentity // menuViewController.feathercoinLabel2.transform = CGAffineTransformIdentity // // menuViewController.namecoinIcon2.transform = CGAffineTransformIdentity // menuViewController.namecoinLabel2.transform = CGAffineTransformIdentity // // menuViewController.peercoinIcon2.transform = CGAffineTransformIdentity // menuViewController.peercoinLabel2.transform = CGAffineTransformIdentity // // menuViewController.blackcoinIcon2.transform = CGAffineTransformIdentity // menuViewController.blackcoinLabel2.transform = CGAffineTransformIdentity } // return how many seconds the transiton animation will take func transitionDuration(transitionContext: UIViewControllerContextTransitioning) -> NSTimeInterval { return 0.6 } // MARK: UIViewControllerTransitioningDelegate protocol methods // return the animataor when presenting a viewcontroller // rememeber that an animator (or animation controller) is any object that aheres to the UIViewControllerAnimatedTransitioning protocol func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = true return self } // return the animator used when dismissing from a viewcontroller func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { self.presenting = false return self } }
9ffb162d9fc9ab9321986a48793a5e5a
45.308642
233
0.709544
false
false
false
false
JGiola/swift
refs/heads/main
test/IRGen/conditional-dead-strip-ir.swift
apache-2.0
9
// Tests that with -conditional-runtime-records, IRGen marks class, struct, // enum, protocol, and protocol conformance records as conditionally removable // via !llvm.used.conditional metadata. // RUN: %target-build-swift -Xfrontend -conditional-runtime-records -Xfrontend -disable-objc-interop %s -emit-ir -o - | %FileCheck %s public protocol TheProtocol { } public class Class: TheProtocol { } public struct Struct { } public enum Enum { } // CHECK: @llvm.{{(compiler.)?}}used = appending global [ // CHECK-SAME: @"$s4main11TheProtocolHr" // CHECK-SAME: @"$s4main5ClassCAA11TheProtocolAAHc" // CHECK-SAME: @"$s4main5ClassCHn" // CHECK-SAME: @"$s4main6StructVHn" // CHECK-SAME: @"$s4main4EnumOHn" // CHECK-SAME: ], section "llvm.metadata" // CHECK: !llvm.used.conditional = !{[[M1:!.*]], [[M2:!.*]], [[M3:!.*]], [[M4:!.*]], [[C1:!.*]], [[C2:!.*]], [[C3:!.*]], [[C4:!.*]], [[C5:!.*]]} // CHECK-DAG: [[M1]] = !{{{.*}} @"$s4main11TheProtocol_pMF", i32 0, [[M1A:!.*]]} // CHECK-DAG: [[M1A]] = {{.*}} @"$s4main11TheProtocolMp" // CHECK-DAG: [[M2]] = !{{{.*}} @"$s4main5ClassCMF", i32 0, [[M2A:!.*]]} // CHECK-DAG: [[M2A]] = {{.*}} @"$s4main5ClassCMn" // CHECK-DAG: [[M3]] = !{{{.*}} @"$s4main6StructVMF", i32 0, [[M3A:!.*]]} // CHECK-DAG: [[M3A]] = {{.*}} @"$s4main6StructVMn" // CHECK-DAG: [[M4]] = !{{{.*}} @"$s4main4EnumOMF", i32 0, [[M4A:!.*]]} // CHECK-DAG: [[M4A]] = {{.*}} @"$s4main4EnumOMn" // CHECK-DAG: [[C1]] = !{{{.*}} @"$s4main11TheProtocolHr", i32 0, [[C1A:!.*]]} // CHECK-DAG: [[C1A]] = {{.*}} @"$s4main11TheProtocolMp"} // CHECK-DAG: [[C2]] = !{{{.*}} @"$s4main5ClassCAA11TheProtocolAAHc", i32 1, [[C2A:!.*]]} // CHECK-DAG: [[C2A]] = {{.*}} @"$s4main11TheProtocolMp", {{.*}} @"$s4main5ClassCMn"} // CHECK-DAG: [[C3]] = !{{{.*}} @"$s4main5ClassCHn", i32 0, [[M2A:!.*]]} // CHECK-DAG: [[C4]] = !{{{.*}} @"$s4main6StructVHn", i32 0, [[M3A:!.*]]} // CHECK-DAG: [[C5]] = !{{{.*}} @"$s4main4EnumOHn", i32 0, [[M4A:!.*]]}
6929e645d6eb6bf80a1d6bbda7b50e84
41.854167
149
0.53087
false
false
false
false
mikecole20/ReSwiftThunk
refs/heads/master
Demo/ReSwiftThunkDemo/ReSwiftThunkDemo/AppReducer.swift
mit
1
// // AppReducer.swift // ReSwiftThunkDemo // // Created by Mike Cole on 11/21/16. // Copyright © 2016 iOS Mike. All rights reserved. // import ReSwift struct AppReducer: Reducer { func handleAction(action: Action, state: AppState?) -> AppState { var state = state ?? AppState() switch action { case _ as ActionLogin: state.loggingIn = true state.loginError = nil case _ as ActionLoginSuccess: state.loggedIn = true state.loggingIn = false case let action as ActionLoginFailure: state.loggingIn = false state.loginError = action.error case _ as ActionLogout: state = AppState() default: break } return state } }
9d99bd56b5c41a622b6eec35881848c7
21.175
69
0.514092
false
false
false
false
alvaromb/EventBlankApp
refs/heads/master
EventBlank/EventBlank/ViewControllers/More/MoreViewController.swift
mit
3
// // MoreViewController.swift // EventBlank // // Created by Marin Todorov on 6/24/15. // Copyright (c) 2015 Underplot ltd. All rights reserved. // import UIKit import SQLite import VTAcknowledgementsViewController class MoreViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! var database: Database { return DatabaseProvider.databases[eventDataFileName]! } var items: [Row] = [] var lastSelectedItem: Row? let extraItems = ["Credits", "Acknowledgements", "Pending Event Update"] func loadItems() { items = database[TextConfig.tableName].filter({Text.content != nil && Text.content != ""}()).order(Text.title.asc).map({$0}) } override func viewDidLoad() { super.viewDidLoad() backgroundQueue(loadItems, completion: { self.tableView.reloadData() }) //notifications observeNotification(kDidReplaceEventFileNotification, selector: "didChangeEventFile") observeNotification(kPendingUpdateChangedNotification, selector: "didChangePendingUpdate") } deinit { //notifications observeNotification(kDidReplaceEventFileNotification, selector: nil) } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let mdvc = segue.destinationViewController as? MDViewController, let item = lastSelectedItem { mdvc.textRow = item } } //MARK: - table view methods func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if section == 0 { return items.count } else { return extraItems.count } } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(indexPath.section == 0 ? "MenuCell" : "ExtraMenuCell") as! UITableViewCell cell.imageView?.image = nil cell.textLabel?.enabled = true cell.accessoryType = .DisclosureIndicator if indexPath.section == 0 { let menuItem = items[indexPath.row] cell.textLabel?.text = menuItem[Text.title] } else { cell.textLabel?.text = extraItems[indexPath.row] let defaults = NSUserDefaults.standardUserDefaults() if indexPath.row == 2 { cell.textLabel?.enabled = defaults.boolForKey("isTherePendingUpdate") if defaults.boolForKey("isTherePendingUpdate") { cell.imageView?.image = UIImage(named: "info-red-empty") } else { cell.accessoryType = .None } } } return cell } func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? { if indexPath.section == 0 { lastSelectedItem = items[indexPath.row] } return indexPath } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if indexPath.section == 1 { switch indexPath.row { case 0: navigationController?.pushViewController(CreditViewController(), animated: true) case 1: let avc = VTAcknowledgementsViewController(acknowledgementsPlistPath: NSBundle.mainBundle().pathForResource("Pods-acknowledgements", ofType: "plist")! ) navigationController?.pushViewController(avc!, animated: true) case 2: let defaults = NSUserDefaults.standardUserDefaults() if defaults.boolForKey("isTherePendingUpdate") { let message = alert("Sending update request - it might take a moment to complete...", buttons: [], completion: nil) delay(seconds: 1.5, { message.dismissViewControllerAnimated(true, completion: { (UIApplication.sharedApplication().delegate as! AppDelegate).updateManager!.triggerRefresh() }) }) } default: break } } } //notifications func didChangeEventFile() { mainQueue({ self.navigationController?.popToRootViewControllerAnimated(true) self.tableView.reloadData() }) } func didChangePendingUpdate() { mainQueue { self.tableView.reloadData() } } }
04b5c5af4b3c5760f4945b5803f2c247
33.914286
137
0.605893
false
false
false
false
imjerrybao/FutureKit
refs/heads/master
FutureKit/FTask/FTask.swift
mit
1
// // NSData-Ext.swift // FutureKit // // Created by Michael Gray on 4/21/15. // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation import CoreData public class FTaskCompletion : NSObject { public typealias rtype = FTask.resultType var completion : Completion<rtype> init(completion c:Completion<rtype>) { self.completion = c } init(exception ex:NSException) { self.completion = FAIL(FutureKitError(exception: ex)) } init(success : rtype) { self.completion = SUCCESS(success) } init(cancelled : ()) { self.completion = .Cancelled(false) } init (fail : ErrorType) { self.completion = FAIL(fail) } init (continueWith f: FTask) { self.completion = COMPLETE_USING(f.future) } class func Success(success : rtype) -> FTaskCompletion { return FTaskCompletion(success: success) } class func Fail(fail : ErrorType) -> FTaskCompletion { return FTaskCompletion(fail: fail) } class func Cancelled() -> FTaskCompletion { return FTaskCompletion(cancelled: ()) } } public class FTaskPromise : NSObject { public override init() { super.init() } public typealias rtype = FTask.resultType var promise = Promise<rtype>() public var ftask : FTask { get { return FTask(self.promise.future) } } public final func complete(completion c: FTaskCompletion) { self.promise.complete(c.completion) } public final func completeWithSuccess(result : rtype) { self.promise.completeWithSuccess(result) } public final func completeWithFail(e : ErrorType) { self.promise.completeWithFail(e) } public final func completeWithException(e : NSException) { self.promise.completeWithException(e) } public final func completeWithCancel() { self.promise.completeWithCancel() } public final func completeUsingFuture(f : FTask) { self.promise.completeUsingFuture(f.future) } // can return true if completion was successful. // can block the current thread final func tryComplete(completion c: FTaskCompletion) -> Bool { return self.promise.tryComplete(c.completion) } public typealias CompletionErrorHandler = Promise<rtype>.CompletionErrorHandler // execute a block if the completion "fails" because the future is already completed. public final func complete(completion c: FTaskCompletion,onCompletionError errorBlock: CompletionErrorHandler) { self.promise.complete(c.completion, onCompletionError: errorBlock) } } extension FTaskPromise : CustomDebugStringConvertible { public override var description: String { return "FTaskPromise!" } public override var debugDescription: String { return "FTaskPromise! - \(self.promise.future.debugDescription)" } public func debugQuickLookObject() -> AnyObject? { return self.debugDescription + "QL" } } @objc public enum FTaskExecutor : Int { case Primary // use the default configured executor. Current set to Immediate. // There are deep philosphical arguments about Immediate vs Async. // So whenever we figure out what's better we will set the Primary to that! case Immediate // Never performs an Async Dispatch, Ok for simple mappings. But use with care! // Blocks using the Immediate executor can run in ANY Block case Async // Always performs an Async Dispatch to some non-main q (usually Default) case StackCheckingImmediate // Will try to perform immediate, but does some stack checking. Safer than Immediate // But is less efficient. Maybe useful if an Immediate handler is somehow causing stack overflow issues case Main // will use MainAsync or MainImmediate based on MainStrategy case MainAsync // will always do a dispatch_async to the mainQ case MainImmediate // will try to avoid dispatch_async if already on the MainQ case UserInteractive // QOS_CLASS_USER_INTERACTIVE case UserInitiated // QOS_CLASS_USER_INITIATED case Default // QOS_CLASS_DEFAULT case Utility // QOS_CLASS_UTILITY case Background // QOS_CLASS_BACKGROUND // case Queue(dispatch_queue_t) // Dispatch to a Queue of your choice! // Use this for your own custom queues // case ManagedObjectContext(NSManagedObjectContext) // block will run inside the managed object's context via context.performBlock() func execute(block b: dispatch_block_t) { let executionBlock = self.executor().callbackBlockFor(b) executionBlock() } func executor() -> Executor { switch self { case .Primary: return .Primary case .Immediate: return .Immediate case .Async: return .Async case StackCheckingImmediate: return .StackCheckingImmediate case Main: return .Main case MainAsync: return .MainAsync case MainImmediate: return .MainImmediate case UserInteractive: return .UserInteractive case UserInitiated: return .UserInitiated case Default: return .Default case Utility: return .Utility case Background: return .Background } } } public class FTask : NSObject { public typealias resultType = AnyObject? public typealias futureType = Future<resultType> var future : Future<resultType> override init() { self.future = Future<resultType>() super.init() } init(_ f : Future<resultType>) { self.future = f } } public extension FTask { private class func toCompletion(a : AnyObject?) -> Completion<resultType> { switch a { case let f as Future<resultType>: return .CompleteUsing(f) case let f as FTask: return .CompleteUsing(f.future) case let c as Completion<resultType>: return c case let c as FTaskCompletion: return c.completion case let error as ErrorType: return .Fail(error) case let ex as NSException: return Completion<resultType>(exception: ex) default: return SUCCESS(a) } } private class func toCompletionObjc(a : AnyObject?) -> FTaskCompletion { return FTaskCompletion(completion: self.toCompletion(a)) } final func onCompleteQ(q : dispatch_queue_t,block b:( (completion:FTaskCompletion)-> AnyObject?)) -> FTask { let f = self.future.onComplete(Executor.Queue(q)) { (completion) -> Completion<resultType> in let c = FTaskCompletion(completion: completion) return FTask.toCompletion(b(completion: c)) } return FTask(f) } final func onComplete(executor : FTaskExecutor,block b:( (completion:FTaskCompletion)-> AnyObject?)) -> FTask { let f = self.future.onComplete(executor.executor()) { (completion) -> Completion<resultType> in let c = FTaskCompletion(completion: completion) return FTask.toCompletion(b(completion: c)) } return FTask(f) } final func onComplete(block:( (completion:FTaskCompletion)-> AnyObject?)) -> FTask { return self.onComplete(.Primary, block: block) } final func onSuccessResultWithQ(q : dispatch_queue_t, _ block:((result:resultType) -> AnyObject?)) -> FTask { return self.onCompleteQ(q) { (c) -> AnyObject? in if c.completion.isSuccess { return block(result: c.completion.result) } else { return c } } } final func onSuccessResultWith(executor : FTaskExecutor, _ block:((result:resultType) -> AnyObject?)) -> FTask { return self.onComplete(executor) { (c) -> AnyObject? in if c.completion.isSuccess { return block(result: c.completion.result) } else { return c } } } final func onSuccessWithQ(q : dispatch_queue_t, block:(() -> AnyObject?)) -> FTask { return self.onCompleteQ(q) { (c) -> AnyObject? in if c.completion.isSuccess { return block() } else { return c } } } final func onSuccess(executor : FTaskExecutor, block:(() -> AnyObject?)) -> FTask { return self.onComplete(executor) { (c) -> AnyObject? in if c.completion.isSuccess { return block() } else { return c } } } final func onSuccessResult(block:((result:resultType)-> AnyObject?)) -> FTask { return self.onSuccessResultWith(.Primary,block) } final func onSuccess(block:(() -> AnyObject?)) -> FTask { return self.onSuccess(.Primary,block: block) } }
bd3a035268615b495ecd9688f7ed7d57
28.566197
138
0.616997
false
false
false
false
ello/ello-ios
refs/heads/master
Sources/Controllers/Profile/Calculators/ProfileHeaderLinksSizeCalculator.swift
mit
1
//// /// ProfileHeaderLinksSizeCalculator.swift // import PromiseKit class ProfileHeaderLinksSizeCalculator: CellSizeCalculator { static func calculateHeight(_ externalLinks: [ExternalLink], width: CGFloat) -> CGFloat { let iconsCount = externalLinks.filter({ $0.iconURL != nil }).count let (perRow, _) = ProfileHeaderLinksSizeCalculator.calculateIconsBoxWidth( externalLinks, width: width ) let iconsRows = max(0, ceil(Double(iconsCount) / Double(perRow))) let iconsHeight = CGFloat(iconsRows) * ProfileHeaderLinksCell.Size.iconSize.height + CGFloat(max(0, iconsRows - 1)) * ProfileHeaderLinksCell.Size.iconMargins let textLinksCount = externalLinks.filter { $0.iconURL == nil && !$0.text.isEmpty }.count let linksHeight = CGFloat(textLinksCount) * ProfileHeaderLinksCell.Size.linkHeight + CGFloat(max(0, textLinksCount - 1)) * ProfileHeaderLinksCell.Size.verticalLinkMargin return ProfileHeaderLinksCell.Size.margins.tops + max(iconsHeight, linksHeight) } static func calculateIconsBoxWidth(_ externalLinks: [ExternalLink], width: CGFloat) -> ( Int, CGFloat ) { let iconsCount = externalLinks.filter({ $0.iconURL != nil }).count let textLinksCount = externalLinks.filter { $0.iconURL == nil && !$0.text.isEmpty }.count let cellWidth = max(0, width - ProfileHeaderLinksCell.Size.margins.sides) let perRow: Int let iconsBoxWidth: CGFloat if textLinksCount > 0 { perRow = 3 let maxNumberOfIconsInRow = CGFloat(min(perRow, iconsCount)) let maxIconsWidth = ProfileHeaderLinksCell.Size.iconSize.width * maxNumberOfIconsInRow let iconsMargins = ProfileHeaderLinksCell.Size.iconMargins * max(0, maxNumberOfIconsInRow - 1) iconsBoxWidth = max(0, maxIconsWidth + iconsMargins) } else { iconsBoxWidth = cellWidth perRow = Int( cellWidth / ( ProfileHeaderLinksCell.Size.iconSize.width + ProfileHeaderLinksCell.Size.iconMargins ) ) } return (perRow, iconsBoxWidth) } override func process() { guard let user = cellItem.jsonable as? User, let externalLinks = user.externalLinksList, externalLinks.count > 0 else { assignCellHeight(all: 0) return } assignCellHeight( all: ProfileHeaderLinksSizeCalculator.calculateHeight(externalLinks, width: width) ) } }
783b61b464860347f3b84d7ab3ef0674
38.25
98
0.632447
false
false
false
false
flodolo/firefox-ios
refs/heads/main
Client/Frontend/Settings/LoginDetailViewController.swift
mpl-2.0
2
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import Storage import Shared enum InfoItem: Int { case breachItem = 0 case websiteItem case usernameItem case passwordItem case lastModifiedSeparator case deleteItem var indexPath: IndexPath { return IndexPath(row: rawValue, section: 0) } } struct LoginDetailUX { static let InfoRowHeight: CGFloat = 58 static let DeleteRowHeight: CGFloat = 44 static let SeparatorHeight: CGFloat = 84 } private class CenteredDetailCell: ThemedTableViewCell, ReusableCell { override func layoutSubviews() { super.layoutSubviews() var f = detailTextLabel?.frame ?? CGRect() f.center = CGPoint(x: frame.center.x - safeAreaInsets.right, y: frame.center.y) detailTextLabel?.frame = f } override func applyTheme(theme: Theme) { super.applyTheme(theme: theme) backgroundColor = theme.colors.layer1 } override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: .subtitle, reuseIdentifier: reuseIdentifier) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } class LoginDetailViewController: SensitiveViewController, Themeable { var themeManager: ThemeManager var themeObserver: NSObjectProtocol? var notificationCenter: NotificationProtocol private let profile: Profile private lazy var tableView: UITableView = .build { [weak self] tableView in guard let self = self else { return } tableView.accessibilityIdentifier = "Login Detail List" tableView.delegate = self tableView.dataSource = self // Add empty footer view to prevent separators from being drawn past the last item. tableView.tableFooterView = UIView() } private weak var websiteField: UITextField? private weak var usernameField: UITextField? private weak var passwordField: UITextField? private var deleteAlert: UIAlertController? weak var settingsDelegate: SettingsDelegate? private var breach: BreachRecord? private var login: LoginRecord { didSet { tableView.reloadData() } } var webpageNavigationHandler: ((_ url: URL?) -> Void)? private var isEditingFieldData: Bool = false { didSet { if isEditingFieldData != oldValue { tableView.reloadData() } } } init(profile: Profile, login: LoginRecord, webpageNavigationHandler: ((_ url: URL?) -> Void)?, themeManager: ThemeManager = AppContainer.shared.resolve(), notificationCenter: NotificationCenter = NotificationCenter.default) { self.login = login self.profile = profile self.webpageNavigationHandler = webpageNavigationHandler self.themeManager = themeManager self.notificationCenter = notificationCenter super.init(nibName: nil, bundle: nil) NotificationCenter.default.addObserver(self, selector: #selector(dismissAlertController), name: UIApplication.didEnterBackgroundNotification, object: nil) } func setBreachRecord(breach: BreachRecord?) { self.breach = breach } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(edit)) tableView.register(cellType: LoginDetailTableViewCell.self) tableView.register(cellType: CenteredDetailCell.self) view.addSubview(tableView) NSLayoutConstraint.activate([ tableView.leadingAnchor.constraint(equalTo: view.leadingAnchor), tableView.topAnchor.constraint(equalTo: view.topAnchor), tableView.trailingAnchor.constraint(equalTo: view.trailingAnchor), tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor) ]) tableView.estimatedRowHeight = 44.0 tableView.separatorInset = .zero applyTheme() listenForThemeChange() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Normally UITableViewControllers handle responding to content inset changes from keyboard events when editing // but since we don't use the tableView's editing flag for editing we handle this ourselves. KeyboardHelper.defaultHelper.addDelegate(self) } func applyTheme() { let theme = themeManager.currentTheme tableView.separatorColor = theme.colors.borderPrimary tableView.backgroundColor = theme.colors.layer1 } } // MARK: - UITableViewDataSource extension LoginDetailViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch InfoItem(rawValue: indexPath.row)! { case .breachItem: guard let breachCell = cell(tableView: tableView, forIndexPath: indexPath) else { return UITableViewCell() } guard let breach = breach else { return breachCell } breachCell.isHidden = false let breachDetailView = BreachAlertsDetailView() breachCell.contentView.addSubview(breachDetailView) NSLayoutConstraint.activate([ breachDetailView.leadingAnchor.constraint(equalTo: breachCell.contentView.leadingAnchor, constant: LoginTableViewCellUX.HorizontalMargin), breachDetailView.topAnchor.constraint(equalTo: breachCell.contentView.topAnchor, constant: LoginTableViewCellUX.HorizontalMargin), breachDetailView.trailingAnchor.constraint(equalTo: breachCell.contentView.trailingAnchor, constant: LoginTableViewCellUX.HorizontalMargin), breachDetailView.bottomAnchor.constraint(equalTo: breachCell.contentView.bottomAnchor, constant: LoginTableViewCellUX.HorizontalMargin) ]) breachDetailView.setup(breach) breachDetailView.learnMoreButton.addTarget(self, action: #selector(LoginDetailViewController.didTapBreachLearnMore), for: .touchUpInside) let breachLinkGesture = UITapGestureRecognizer(target: self, action: #selector(LoginDetailViewController .didTapBreachLink(_:))) breachDetailView.goToButton.addGestureRecognizer(breachLinkGesture) breachCell.isAccessibilityElement = false breachCell.contentView.accessibilityElementsHidden = true breachCell.accessibilityElements = [breachDetailView] breachCell.applyTheme(theme: themeManager.currentTheme) return breachCell case .usernameItem: guard let loginCell = cell(tableView: tableView, forIndexPath: indexPath) else { return UITableViewCell() } loginCell.highlightedLabelTitle = .LoginDetailUsername loginCell.descriptionLabel.text = login.decryptedUsername loginCell.descriptionLabel.keyboardType = .emailAddress loginCell.descriptionLabel.returnKeyType = .next loginCell.isEditingFieldData = isEditingFieldData usernameField = loginCell.descriptionLabel usernameField?.accessibilityIdentifier = "usernameField" loginCell.applyTheme(theme: themeManager.currentTheme) return loginCell case .passwordItem: guard let loginCell = cell(tableView: tableView, forIndexPath: indexPath) else { return UITableViewCell() } loginCell.highlightedLabelTitle = .LoginDetailPassword loginCell.descriptionLabel.text = login.decryptedPassword loginCell.descriptionLabel.returnKeyType = .default loginCell.displayDescriptionAsPassword = true loginCell.isEditingFieldData = isEditingFieldData setCellSeparatorHidden(loginCell) passwordField = loginCell.descriptionLabel passwordField?.accessibilityIdentifier = "passwordField" loginCell.applyTheme(theme: themeManager.currentTheme) return loginCell case .websiteItem: guard let loginCell = cell(tableView: tableView, forIndexPath: indexPath) else { return UITableViewCell() } loginCell.highlightedLabelTitle = .LoginDetailWebsite loginCell.descriptionLabel.text = login.hostname websiteField = loginCell.descriptionLabel websiteField?.accessibilityIdentifier = "websiteField" loginCell.isEditingFieldData = false if isEditingFieldData { loginCell.contentView.alpha = 0.5 } loginCell.applyTheme(theme: themeManager.currentTheme) return loginCell case .lastModifiedSeparator: guard let cell = tableView.dequeueReusableCell(withIdentifier: CenteredDetailCell.cellIdentifier, for: indexPath) as? CenteredDetailCell else { return UITableViewCell() } let created: String = .LoginDetailCreatedAt let lastModified: String = .LoginDetailModifiedAt let lastModifiedFormatted = String(format: lastModified, Date.fromTimestamp(UInt64(login.timePasswordChanged)).toRelativeTimeString(dateStyle: .medium)) let createdFormatted = String(format: created, Date.fromTimestamp(UInt64(login.timeCreated)).toRelativeTimeString(dateStyle: .medium, timeStyle: .none)) // Setting only the detail text produces smaller text as desired, and it is centered. cell.detailTextLabel?.text = createdFormatted + "\n" + lastModifiedFormatted cell.detailTextLabel?.numberOfLines = 2 cell.detailTextLabel?.textAlignment = .center setCellSeparatorHidden(cell) cell.applyTheme(theme: themeManager.currentTheme) return cell case .deleteItem: guard let deleteCell = cell(tableView: tableView, forIndexPath: indexPath) else { return UITableViewCell() } deleteCell.textLabel?.text = .LoginDetailDelete deleteCell.textLabel?.textAlignment = .center deleteCell.accessibilityTraits = UIAccessibilityTraits.button deleteCell.configure(type: .delete) deleteCell.applyTheme(theme: themeManager.currentTheme) setCellSeparatorFullWidth(deleteCell) return deleteCell } } private func cell(tableView: UITableView, forIndexPath indexPath: IndexPath) -> LoginDetailTableViewCell? { guard let cell = tableView.dequeueReusableCell(withIdentifier: LoginDetailTableViewCell.cellIdentifier, for: indexPath) as? LoginDetailTableViewCell else { return nil } cell.selectionStyle = .none cell.delegate = self return cell } private func setCellSeparatorHidden(_ cell: UITableViewCell) { // Prevent seperator from showing by pushing it off screen by the width of the cell cell.separatorInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: view.frame.width) } private func setCellSeparatorFullWidth(_ cell: UITableViewCell) { cell.separatorInset = .zero cell.layoutMargins = .zero cell.preservesSuperviewLayoutMargins = false } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 6 } } // MARK: - UITableViewDelegate extension LoginDetailViewController: UITableViewDelegate { private func showMenuOnSingleTap(forIndexPath indexPath: IndexPath) { guard let item = InfoItem(rawValue: indexPath.row) else { return } if ![InfoItem.passwordItem, InfoItem.websiteItem, InfoItem.usernameItem].contains(item) { return } guard let cell = tableView.cellForRow(at: indexPath) as? LoginDetailTableViewCell else { return } cell.becomeFirstResponder() let menu = UIMenuController.shared menu.showMenu(from: tableView, rect: cell.frame) } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath == InfoItem.deleteItem.indexPath { deleteLogin() } else if !isEditingFieldData { showMenuOnSingleTap(forIndexPath: indexPath) } tableView.deselectRow(at: indexPath, animated: true) } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { switch InfoItem(rawValue: indexPath.row)! { case .breachItem: guard breach != nil else { return 0 } return UITableView.automaticDimension case .usernameItem, .passwordItem, .websiteItem: return LoginDetailUX.InfoRowHeight case .lastModifiedSeparator: return LoginDetailUX.SeparatorHeight case .deleteItem: return LoginDetailUX.DeleteRowHeight } } } // MARK: - KeyboardHelperDelegate extension LoginDetailViewController: KeyboardHelperDelegate { func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) { let coveredHeight = state.intersectionHeightForView(tableView) tableView.contentInset.bottom = coveredHeight } func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) { tableView.contentInset.bottom = 0 } } // MARK: - Selectors extension LoginDetailViewController { @objc func dismissAlertController() { deleteAlert?.dismiss(animated: false, completion: nil) } @objc func didTapBreachLearnMore() { webpageNavigationHandler?(BreachAlertsManager.monitorAboutUrl) } @objc func didTapBreachLink(_ sender: UITapGestureRecognizer? = nil) { guard let domain = breach?.domain else { return } var urlComponents = URLComponents() urlComponents.host = domain urlComponents.scheme = "https" webpageNavigationHandler?(urlComponents.url) } func deleteLogin() { profile.hasSyncedLogins().uponQueue(.main) { yes in self.deleteAlert = UIAlertController.deleteLoginAlertWithDeleteCallback({ [unowned self] _ in self.profile.logins.deleteLogin(id: self.login.id).uponQueue(.main) { _ in _ = self.navigationController?.popViewController(animated: true) } }, hasSyncedLogins: yes.successValue ?? true) self.present(self.deleteAlert!, animated: true, completion: nil) } } func onProfileDidFinishSyncing() { // Reload details after syncing. profile.logins.getLogin(id: login.id).uponQueue(.main) { result in if let successValue = result.successValue, let syncedLogin = successValue { self.login = syncedLogin } } } @objc func edit() { isEditingFieldData = true guard let cell = tableView.cellForRow(at: InfoItem.usernameItem.indexPath) as? LoginDetailTableViewCell else { return } cell.descriptionLabel.becomeFirstResponder() navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(doneEditing)) } @objc func doneEditing() { isEditingFieldData = false navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(edit)) // Only update if user made changes guard let username = usernameField?.text, let password = passwordField?.text else { return } guard username != login.decryptedUsername || password != login.decryptedPassword else { return } let updatedLogin = LoginEntry( fromLoginEntryFlattened: LoginEntryFlattened( id: login.id, hostname: login.hostname, password: password, username: username, httpRealm: login.httpRealm, formSubmitUrl: login.formSubmitUrl, usernameField: login.usernameField, passwordField: login.passwordField ) ) if updatedLogin.isValid.isSuccess { profile.logins.updateLogin(id: login.id, login: updatedLogin).uponQueue(.main) { _ in self.onProfileDidFinishSyncing() // Required to get UI to reload with changed state self.tableView.reloadData() } } } } // MARK: - Cell Delegate extension LoginDetailViewController: LoginDetailTableViewCellDelegate { func textFieldDidEndEditing(_ cell: LoginDetailTableViewCell) { } func textFieldDidChange(_ cell: LoginDetailTableViewCell) { } func canPerform(action: Selector, for cell: LoginDetailTableViewCell) -> Bool { guard let item = infoItemForCell(cell) else { return false } switch item { case .websiteItem: // Menu actions for Website return action == MenuHelper.SelectorCopy || action == MenuHelper.SelectorOpenAndFill case .usernameItem: // Menu actions for Username return action == MenuHelper.SelectorCopy case .passwordItem: // Menu actions for password let showRevealOption = cell.descriptionLabel.isSecureTextEntry ? (action == MenuHelper.SelectorReveal) : (action == MenuHelper.SelectorHide) return action == MenuHelper.SelectorCopy || showRevealOption default: return false } } private func cellForItem(_ item: InfoItem) -> LoginDetailTableViewCell? { return tableView.cellForRow(at: item.indexPath) as? LoginDetailTableViewCell } func didSelectOpenAndFillForCell(_ cell: LoginDetailTableViewCell) { guard let url = (login.formSubmitUrl?.asURL ?? login.hostname.asURL) else { return } navigationController?.dismiss(animated: true, completion: { self.settingsDelegate?.settingsOpenURLInNewTab(url) }) } func shouldReturnAfterEditingDescription(_ cell: LoginDetailTableViewCell) -> Bool { let usernameCell = cellForItem(.usernameItem) let passwordCell = cellForItem(.passwordItem) if cell == usernameCell { passwordCell?.descriptionLabel.becomeFirstResponder() } return false } func infoItemForCell(_ cell: LoginDetailTableViewCell) -> InfoItem? { if let index = tableView.indexPath(for: cell), let item = InfoItem(rawValue: index.row) { return item } return nil } }
e12c7e8c9ac5b6dd28fc6bde0c37d6c8
39.675789
164
0.667253
false
false
false
false
nickqiao/NKBill
refs/heads/master
Carthage/Checkouts/PagingMenuController/Pod/Classes/PagingMenuController.swift
apache-2.0
1
// // PagingMenuController.swift // PagingMenuController // // Created by Yusuke Kita on 3/18/15. // Copyright (c) 2015 kitasuke. All rights reserved. // import UIKit @objc public protocol PagingMenuControllerDelegate: class { optional func willMoveToPageMenuController(menuController: UIViewController, previousMenuController: UIViewController) optional func didMoveToPageMenuController(menuController: UIViewController, previousMenuController: UIViewController) } public class PagingMenuController: UIViewController { weak public var delegate: PagingMenuControllerDelegate? public private(set) var menuView: MenuView! public private(set) var currentPage: Int = 0 public private(set) var currentViewController: UIViewController! public private(set) var visiblePagingViewControllers = [UIViewController]() public private(set) var pagingViewControllers = [UIViewController]() { willSet { options.menuItemCount = newValue.count options.menuItemViewContent = newValue.flatMap({ $0.menuItemImage }).isEmpty ? .Text : .Image switch options.menuItemViewContent { case .Text: menuItemTitles = newValue.map { $0.title ?? "Menu" } case .Image: menuItemImages = newValue.map { $0.menuItemImage ?? UIImage() } } } didSet { cleanup() } } private var options: PagingMenuOptions! private let visiblePagingViewNumber: Int = 3 private let contentScrollView: UIScrollView = { let scrollView = UIScrollView(frame: .zero) scrollView.pagingEnabled = true scrollView.showsHorizontalScrollIndicator = false scrollView.showsVerticalScrollIndicator = false scrollView.scrollsToTop = false scrollView.bounces = false scrollView.translatesAutoresizingMaskIntoConstraints = false return scrollView }() private let contentView: UIView = { let view = UIView(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false return view }() private var menuItemTitles: [String] = [] private var menuItemImages: [UIImage] = [] private enum PagingViewPosition { case Left, Center, Right, Unknown init(order: Int) { switch order { case 0: self = .Left case 1: self = .Center case 2: self = .Right default: self = .Unknown } } } private var previousIndex: Int { guard case .Infinite = options.menuDisplayMode else { return currentPage - 1 } return currentPage - 1 < 0 ? options.menuItemCount - 1 : currentPage - 1 } private var nextIndex: Int { guard case .Infinite = options.menuDisplayMode else { return currentPage + 1 } return currentPage + 1 > options.menuItemCount - 1 ? 0 : currentPage + 1 } private var currentPagingViewPosition: PagingViewPosition { let pageWidth = contentScrollView.frame.width let order = Int(ceil((contentScrollView.contentOffset.x - pageWidth / 2) / pageWidth)) if case .Infinite = options.menuDisplayMode { return PagingViewPosition(order: order) } // consider left edge menu as center position guard currentPage == 0 && contentScrollView.contentSize.width < (pageWidth * CGFloat(visiblePagingViewNumber)) else { return PagingViewPosition(order: order) } return PagingViewPosition(order: order + 1) } lazy private var shouldLoadPage: (Int) -> Bool = { [unowned self] in switch (self.options.menuControllerSet, self.options.lazyLoadingPage) { case (.Single, _), (_, .One): guard $0 == self.currentPage else { return false } case (_, .Three): if case .Infinite = self.options.menuDisplayMode { guard $0 == self.currentPage || $0 == self.previousIndex || $0 == self.nextIndex else { return false } } else { guard $0 >= self.previousIndex && $0 <= self.nextIndex else { return false } } } return true } lazy private var isVisiblePagingViewController: (UIViewController) -> Bool = { [unowned self] in return self.childViewControllers.contains($0) } private let ExceptionName = "PMCException" // MARK: - Lifecycle public init(viewControllers: [UIViewController], options: PagingMenuOptions) { super.init(nibName: nil, bundle: nil) setup(viewControllers, options: options) } convenience public init(viewControllers: [UIViewController]) { self.init(viewControllers: viewControllers, options: PagingMenuOptions()) } public init(menuItemTypes: [MenuItemType], options: PagingMenuOptions) { super.init(nibName: nil, bundle: nil) setup(menuItemTypes, options: options) } convenience public init(menuItemTypes: [MenuItemType]) { self.init(menuItemTypes: menuItemTypes, options: PagingMenuOptions()) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } public override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) positionMenuController() } override public func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() // fix unnecessary inset for menu view when implemented by programmatically menuView?.contentInset.top = 0 // position paging views correctly after view size is decided positionMenuController() } override public func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) if let menuView = menuView { menuView.updateMenuViewConstraints(size: size) coordinator.animateAlongsideTransition({ [unowned self] (_) -> Void in self.view.setNeedsLayout() self.view.layoutIfNeeded() // reset selected menu item view position switch self.options.menuDisplayMode { case .Standard, .Infinite: self.moveToMenuPage(self.currentPage, animated: true) default: break } }, completion: nil) } } // MARK: - Public public func setup(viewControllers: [UIViewController], options: PagingMenuOptions) { self.options = options pagingViewControllers = viewControllers visiblePagingViewControllers.reserveCapacity(visiblePagingViewNumber) // validate validateDefaultPage() validatePageNumbers() currentPage = options.defaultPage setupMenuView() setupMenuController() currentViewController = pagingViewControllers[currentPage] moveToMenuPage(currentPage, animated: false) } private func setupMenuView() { switch options.menuComponentType { case .MenuController: return default: break } constructMenuView() layoutMenuView() } private func setupMenuController() { switch options.menuComponentType { case .MenuView: return default: break } setupContentScrollView() layoutContentScrollView() setupContentView() layoutContentView() constructPagingViewControllers() layoutPagingViewControllers() } public func setup(menuItemTypes: [MenuItemType], options: PagingMenuOptions) { self.options = options currentPage = options.defaultPage options.menuComponentType = .MenuView if let title = menuItemTypes.first where title is String { options.menuItemViewContent = .Text menuItemTitles = menuItemTypes.map { $0 as! String } } else if let image = menuItemTypes.first where image is UIImage { options.menuItemViewContent = .Image menuItemImages = menuItemTypes.map { $0 as! UIImage } } setupMenuView() menuView.moveToMenu(currentPage, animated: false) } public func moveToMenuPage(page: Int, animated: Bool = true) { switch options.menuComponentType { case .MenuView, .All: // ignore an unexpected page number guard page < menuView.menuItemCount else { return } let lastPage = menuView.currentPage guard page != lastPage else { // place views on appropriate position menuView.moveToMenu(page, animated: animated) positionMenuController() return } guard options.menuComponentType == .All else { updateCurrentPage(page) menuView.moveToMenu(page, animated: animated) return } case .MenuController: guard page < pagingViewControllers.count else { return } guard page != currentPage else { return } } // hide paging views if it's moving to far away hidePagingMenuControllers(page) let previousViewController = currentViewController delegate?.willMoveToPageMenuController?(currentViewController, previousMenuController: previousViewController) updateCurrentPage(page) currentViewController = pagingViewControllers[currentPage] menuView?.moveToMenu(page) let duration = animated ? options.animationDuration : 0 UIView.animateWithDuration(duration, animations: { [unowned self] () -> Void in self.positionMenuController() }) { [weak self] (_) -> Void in guard let _ = self else { return } self!.relayoutPagingViewControllers() // show paging views self!.showPagingMenuControllers() self!.delegate?.didMoveToPageMenuController?(self!.currentViewController, previousMenuController: previousViewController) } } // MARK: - UIGestureRecognizer internal func handleTapGesture(recognizer: UITapGestureRecognizer) { guard let menuItemView = recognizer.view as? MenuItemView else { return } guard let page = menuView.menuItemViews.indexOf(menuItemView) where page != menuView.currentPage else { return } let newPage: Int switch self.options.menuDisplayMode { case .Standard(_, _, .PagingEnabled): newPage = page < self.currentPage ? self.currentPage - 1 : self.currentPage + 1 case .Infinite(_, .PagingEnabled): if menuItemView.frame.midX > menuView.currentMenuItemView.frame.midX { newPage = menuView.nextPage } else { newPage = menuView.previousPage } case .Infinite: fallthrough default: newPage = page } moveToMenuPage(newPage) } internal func handleSwipeGesture(recognizer: UISwipeGestureRecognizer) { guard let menuView = recognizer.view as? MenuView else { return } let newPage: Int switch (recognizer.direction, options.menuDisplayMode) { case (UISwipeGestureRecognizerDirection.Left, .Infinite): newPage = menuView.nextPage case (UISwipeGestureRecognizerDirection.Left, _): newPage = min(nextIndex, options.menuItemCount - 1) case (UISwipeGestureRecognizerDirection.Right, .Infinite): newPage = menuView.previousPage case (UISwipeGestureRecognizerDirection.Right, _): newPage = max(previousIndex, 0) default: return } moveToMenuPage(newPage) } // MARK: - Constructor private func constructMenuView() { switch options.menuComponentType { case .MenuController: return default: break } switch options.menuItemViewContent { case .Text: menuView = MenuView(menuItemTypes: menuItemTitles, options: options) case .Image: menuView = MenuView(menuItemTypes: menuItemImages, options: options) } menuView.delegate = self view.addSubview(menuView) addTapGestureHandlers() addSwipeGestureHandlersIfNeeded() } private func layoutMenuView() { let viewsDictionary = ["menuView": menuView] let verticalConstraints: [NSLayoutConstraint] switch options.menuComponentType { case .All: switch options.menuPosition { case .Top: verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[menuView]", options: [], metrics: nil, views: viewsDictionary) case .Bottom: verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[menuView]|", options: [], metrics: nil, views: viewsDictionary) } case .MenuView: verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[menuView]", options: [], metrics: nil, views: viewsDictionary) default: return } let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[menuView]|", options: [], metrics: nil, views: viewsDictionary) NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints) menuView.setNeedsLayout() menuView.layoutIfNeeded() } private func setupContentScrollView() { contentScrollView.delegate = self contentScrollView.scrollEnabled = options.scrollEnabled view.addSubview(contentScrollView) } private func layoutContentScrollView() { let viewsDictionary: [String: UIView] switch options.menuComponentType { case .MenuController: viewsDictionary = ["contentScrollView": contentScrollView] default: viewsDictionary = ["contentScrollView": contentScrollView, "menuView": menuView] } let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentScrollView]|", options: [], metrics: nil, views: viewsDictionary) let verticalConstraints: [NSLayoutConstraint] switch (options.menuComponentType, options.menuPosition) { case (.MenuController, _): verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[contentScrollView]|", options: [], metrics: nil, views: viewsDictionary) case (_, .Top): verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[menuView][contentScrollView]|", options: [], metrics: nil, views: viewsDictionary) case (_, .Bottom): verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[contentScrollView][menuView]", options: [], metrics: nil, views: viewsDictionary) } NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints) } private func setupContentView() { contentScrollView.addSubview(contentView) } private func layoutContentView() { let viewsDictionary = ["contentView": contentView, "contentScrollView": contentScrollView] let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[contentView]|", options: [], metrics: nil, views: viewsDictionary) let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[contentView(==contentScrollView)]|", options: [], metrics: nil, views: viewsDictionary) NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints) } private func constructPagingViewControllers() { for (index, pagingViewController) in pagingViewControllers.enumerate() { // construct three child view controllers at a maximum, previous(optional), current and next(optional) if !shouldLoadPage(index) { // remove unnecessary child view controllers if isVisiblePagingViewController(pagingViewController) { pagingViewController.willMoveToParentViewController(nil) pagingViewController.view!.removeFromSuperview() pagingViewController.removeFromParentViewController() if let viewIndex = visiblePagingViewControllers.indexOf(pagingViewController) { visiblePagingViewControllers.removeAtIndex(viewIndex) } } continue } // ignore if it's already added if isVisiblePagingViewController(pagingViewController) { continue } guard let pagingView = pagingViewController.view else { fatalError("\(pagingViewController) doesn't have any view") } pagingView.frame = .zero pagingView.translatesAutoresizingMaskIntoConstraints = false contentView.addSubview(pagingView) addChildViewController(pagingViewController as UIViewController) pagingViewController.didMoveToParentViewController(self) visiblePagingViewControllers.append(pagingViewController) } } private func layoutPagingViewControllers() { // cleanup NSLayoutConstraint.deactivateConstraints(contentView.constraints) var viewsDictionary: [String: AnyObject] = ["contentScrollView": contentScrollView] for (index, pagingViewController) in pagingViewControllers.enumerate() { if !shouldLoadPage(index) { continue } viewsDictionary["pagingView"] = pagingViewController.view! var horizontalVisualFormat = String() // only one view controller if options.menuItemCount == options.minumumSupportedViewCount || options.lazyLoadingPage == .One || options.menuControllerSet == .Single { horizontalVisualFormat = "H:|[pagingView(==contentScrollView)]|" } else { if case .Infinite = options.menuDisplayMode { if index == currentPage { viewsDictionary["previousPagingView"] = pagingViewControllers[previousIndex].view viewsDictionary["nextPagingView"] = pagingViewControllers[nextIndex].view horizontalVisualFormat = "H:[previousPagingView][pagingView(==contentScrollView)][nextPagingView]" } else if index == previousIndex { horizontalVisualFormat = "H:|[pagingView(==contentScrollView)]" } else if index == nextIndex { horizontalVisualFormat = "H:[pagingView(==contentScrollView)]|" } } else { if index == 0 || index == previousIndex { horizontalVisualFormat = "H:|[pagingView(==contentScrollView)]" } else { viewsDictionary["previousPagingView"] = pagingViewControllers[index - 1].view if index == pagingViewControllers.count - 1 || index == nextIndex { horizontalVisualFormat = "H:[previousPagingView][pagingView(==contentScrollView)]|" } else { horizontalVisualFormat = "H:[previousPagingView][pagingView(==contentScrollView)]" } } } } let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat(horizontalVisualFormat, options: [], metrics: nil, views: viewsDictionary) let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|[pagingView(==contentScrollView)]|", options: [], metrics: nil, views: viewsDictionary) NSLayoutConstraint.activateConstraints(horizontalConstraints + verticalConstraints) } view.setNeedsLayout() view.layoutIfNeeded() } private func relayoutPagingViewControllers() { constructPagingViewControllers() layoutPagingViewControllers() view.setNeedsLayout() view.layoutIfNeeded() } // MARK: - Cleanup private func cleanup() { visiblePagingViewControllers.removeAll() currentViewController = nil childViewControllers.forEach { $0.willMoveToParentViewController(nil) $0.view.removeFromSuperview() $0.removeFromParentViewController() } if let menuView = self.menuView { menuView.cleanup() menuView.removeFromSuperview() contentScrollView.removeFromSuperview() } } // MARK: - Private private func positionMenuController() { if let currentViewController = currentViewController, let currentView = currentViewController.view { contentScrollView.contentOffset.x = currentView.frame.minX } } private func updateCurrentPage(page: Int) { let currentPage = page % options.menuItemCount self.currentPage = currentPage } private func hidePagingMenuControllers(page: Int) { switch (options.lazyLoadingPage, options.menuDisplayMode, page) { case (.Three, .Infinite, menuView?.previousPage ?? previousIndex), (.Three, .Infinite, menuView?.nextPage ?? nextIndex), (.Three, _, previousIndex), (.Three, _, nextIndex): break default: visiblePagingViewControllers.forEach { $0.view.alpha = 0 } } } private func showPagingMenuControllers() { visiblePagingViewControllers.forEach { $0.view.alpha = 1 } } // MARK: - Gesture handler private func addTapGestureHandlers() { menuView.menuItemViews.forEach { let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(PagingMenuController.handleTapGesture(_:))) gestureRecognizer.numberOfTapsRequired = 1 $0.addGestureRecognizer(gestureRecognizer) } } private func addSwipeGestureHandlersIfNeeded() { switch options.menuDisplayMode { case .Standard(_, _, .PagingEnabled): break case .Infinite(_, .PagingEnabled): break default: return } let leftSwipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(PagingMenuController.handleSwipeGesture(_:))) leftSwipeGesture.direction = .Left menuView.panGestureRecognizer.requireGestureRecognizerToFail(leftSwipeGesture) menuView.addGestureRecognizer(leftSwipeGesture) let rightSwipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(PagingMenuController.handleSwipeGesture(_:))) rightSwipeGesture.direction = .Right menuView.panGestureRecognizer.requireGestureRecognizerToFail(rightSwipeGesture) menuView.addGestureRecognizer(rightSwipeGesture) } // MARK: - Validator private func validateDefaultPage() { guard options.defaultPage >= options.menuItemCount || options.defaultPage < 0 else { return } NSException(name: ExceptionName, reason: "default page is invalid", userInfo: nil).raise() } private func validatePageNumbers() { guard case .Infinite = options.menuDisplayMode else { return } guard options.menuItemCount < visiblePagingViewNumber else { return } NSException(name: ExceptionName, reason: "the number of view controllers should be more than three with Infinite display mode", userInfo: nil).raise() } } extension PagingMenuController: UIScrollViewDelegate { private var nextPageFromCurrentPosition: Int { // set new page number according to current moving direction let nextPage: Int switch currentPagingViewPosition { case .Left: nextPage = options.menuComponentType == .MenuController ? previousIndex : menuView.previousPage case .Right: nextPage = options.menuComponentType == .MenuController ? nextIndex : menuView.nextPage default: nextPage = currentPage } return nextPage } private var nextPageFromCurrentPoint: Int { let point = CGPointMake(menuView.contentOffset.x + menuView.frame.width / 2, 0) for (index, menuItemView) in menuView.menuItemViews.enumerate() { guard CGRectContainsPoint(menuItemView.frame, point) else { continue } return index } return currentPage } // MARK: - UIScrollViewDelegate public func scrollViewDidEndDecelerating(scrollView: UIScrollView) { let nextPage: Int switch scrollView { case let scrollView where scrollView.isEqual(contentScrollView): nextPage = nextPageFromCurrentPosition case let scrollView where scrollView.isEqual(menuView): nextPage = nextPageFromCurrentPoint default: return } moveToMenuPage(nextPage) } public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) { switch (scrollView, decelerate) { case (let scrollView, false) where scrollView.isEqual(menuView): break default: return } let nextPage = nextPageFromCurrentPoint moveToMenuPage(nextPage) } }
f2d5b04ae436c6bf15b1909027e0d7f6
39.621329
176
0.631559
false
false
false
false
neopixl/NPFlipButton
refs/heads/master
NPButtonFlip/Classes/NPFlipView/NPFlipView.swift
apache-2.0
1
/* Copyright 2015 NEOPIXL S.A. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ import UIKit public class NPFlipView: UIControl { private var frontImageView=UIImageView() private var backImageView=UIImageView() private var backDisplayed = false private var completionBlock:(() -> Void)? // MARK: - init override init(frame: CGRect) { super.init(frame: frame) self.addSubview(frontImageView) self.addSubview(backImageView) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.addSubview(frontImageView) self.addSubview(backImageView) } // MARK: - set front and back Images public func setImages(frontImage: UIImage, backImage: UIImage) { self.frontImageView.image = frontImage self.frontImageView.frame.size = frontImage.size self.backImageView.image = backImage self.backImageView.frame.size = backImage.size self.enableSadow() } // MARK: - Disable Shadow on Image public func disableShadow() { self.frontImageView.layer.shadowColor = nil self.frontImageView.layer.shadowOpacity = 1 self.frontImageView.layer.shadowOffset = CGSize() self.frontImageView.layer.shadowRadius = 0 self.frontImageView.layer.masksToBounds = false self.frontImageView.layer.zPosition = 0 self.frontImageView.layer.shouldRasterize = true self.backImageView.layer.shadowColor = nil self.backImageView.layer.shadowOpacity = 1 self.backImageView.layer.shadowOffset = CGSize() self.backImageView.layer.shadowRadius = 0 self.backImageView.layer.masksToBounds = false self.backImageView.layer.zPosition = 0 self.backImageView.layer.shouldRasterize = true } // MARK: - Enable Shadow on Image public func enableSadow() { self.frontImageView.layer.shadowColor = UIColor.black.cgColor self.frontImageView.layer.shadowOpacity = 0.25 self.frontImageView.layer.shadowOffset = CGSize(width: 0, height: 2) self.frontImageView.layer.shadowRadius = 2 self.frontImageView.layer.masksToBounds = false self.frontImageView.layer.zPosition = -1 self.frontImageView.layer.shouldRasterize = true self.backImageView.layer.shadowColor = UIColor.black.cgColor self.backImageView.layer.shadowOpacity = 0.25 self.backImageView.layer.shadowOffset = CGSize(width: 0, height: 2) self.backImageView.layer.shadowRadius = 2 self.backImageView.layer.masksToBounds = false self.backImageView.layer.zPosition = -1 self.backImageView.layer.shouldRasterize = true } // MARK: - touches Management public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { self.sendActions(for: .touchDown) } public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { self.sendActions(for: .touchUpInside) } // MARK: - flip public func flip(animated: Bool, duration: TimeInterval, completionBlock:(() -> Void)!) { if animated { UIView.transition(with: self, duration: 0.3, options: .transitionFlipFromRight, animations: { //animations if !self.backDisplayed { self.backImageView.removeFromSuperview() self.addSubview(self.frontImageView) } else { self.frontImageView.removeFromSuperview() self.addSubview(self.backImageView) } self.backDisplayed = !self.backDisplayed }, completion: { (finished) in if let block = completionBlock { block() } }) } else { if !self.backDisplayed { self.backImageView.removeFromSuperview() self.addSubview(self.frontImageView) } else { self.frontImageView.removeFromSuperview() self.addSubview(self.backImageView) } if let block = completionBlock { block() } } } public func flip(animated: Bool, duration: TimeInterval, toBack: Bool, completionBlock: ((Bool) -> Void)!) { if(toBack != backDisplayed) { if animated { UIView.transition(with: self, duration: 0.3, options: .transitionFlipFromRight, animations: { //animations if toBack { self.backImageView.removeFromSuperview() self.addSubview(self.frontImageView) } else { self.frontImageView.removeFromSuperview() self.addSubview(self.backImageView) } self.backDisplayed = toBack }, completion: { (finished) in if let block = completionBlock { block(finished) } }) } else { if toBack { self.backImageView.removeFromSuperview() self.addSubview(self.frontImageView) } else { self.frontImageView.removeFromSuperview() self.addSubview(self.backImageView) } self.backDisplayed = toBack if let block = completionBlock { block(true) } } } } }
3f6072b3614ad5764191452261218545
33.544379
112
0.635149
false
false
false
false
FotiosTragopoulos/Core-Geometry
refs/heads/master
Core Geometry/Rho3ViewLine.swift
apache-2.0
1
// // Rho3ViewLine.swift // Core Geometry // // Created by Fotios Tragopoulos on 16/01/2017. // Copyright © 2017 Fotios Tragopoulos. All rights reserved. // import UIKit class Rho3ViewLine: UIView { override func draw(_ rect: CGRect) { let context = UIGraphicsGetCurrentContext() let myShadowOffset = CGSize (width: 10, height: 10) context?.setShadow (offset: myShadowOffset, blur: 8) context?.saveGState() context?.setLineWidth(3.0) context?.setStrokeColor(UIColor.red.cgColor) let xView = viewWithTag(29)?.alignmentRect(forFrame: rect).midX let yView = viewWithTag(29)?.alignmentRect(forFrame: rect).midY let width = self.viewWithTag(29)?.frame.size.width let height = self.viewWithTag(29)?.frame.size.height let size = CGSize(width: width! * 0.8, height: height! * 0.8) let rectPlacementY = CGFloat(size.height/2) let center = CGPoint(x: xView!, y: (yView! + rectPlacementY)) let radius = CGFloat(xView! * 0.2) let startAngle = CGFloat(4.0) let endAngle = CGFloat(5.4) context?.addArc(center: center, radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false) context?.strokePath() context?.restoreGState() self.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) UIView.animate(withDuration: 1.0, delay: 0, usingSpringWithDamping: 0.15, initialSpringVelocity: 6.0, options: .allowUserInteraction, animations: { self.transform = CGAffineTransform.identity } ,completion: nil) } }
508aadd2c389e6edb0bb403340d59f11
35.23913
219
0.635273
false
false
false
false
mrommel/TreasureDungeons
refs/heads/master
TreasureDungeons/Source/OpenGL/Matrix4.swift
apache-2.0
1
// // Matrix4.swift // TreasureDungeons // // Created by Michael Rommel on 26.06.17. // Copyright © 2017 BurtK. All rights reserved. // import Foundation import GLKit extension Float { var radians: Float { return GLKMathDegreesToRadians(self) } } public class Matrix4 { var glkMatrix: GLKMatrix4 public static let identity = Matrix4(1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1) static func makePerspectiveView(angle: Float, aspectRatio: Float, nearZ: Float, farZ: Float) -> Matrix4 { let matrix = Matrix4() matrix.glkMatrix = GLKMatrix4MakePerspective(angle, aspectRatio, nearZ, farZ) return matrix } init() { glkMatrix = GLKMatrix4Identity } public convenience init(_ m11: Float, _ m12: Float, _ m13: Float, _ m14: Float, _ m21: Float, _ m22: Float, _ m23: Float, _ m24: Float, _ m31: Float, _ m32: Float, _ m33: Float, _ m34: Float, _ m41: Float, _ m42: Float, _ m43: Float, _ m44: Float) { self.init() self.glkMatrix.m = (m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44) } func copy() -> Matrix4 { let newMatrix = Matrix4() newMatrix.glkMatrix = self.glkMatrix return newMatrix } func scale(x: Float, y: Float, z: Float) { glkMatrix = GLKMatrix4Scale(glkMatrix, x, y, z) } func rotateAround(x: Float, y: Float, z: Float) { glkMatrix = GLKMatrix4Rotate(glkMatrix, x, 1, 0, 0) glkMatrix = GLKMatrix4Rotate(glkMatrix, y, 0, 1, 0) glkMatrix = GLKMatrix4Rotate(glkMatrix, z, 0, 0, 1) } func translate(x: Float, y: Float, z: Float) { glkMatrix = GLKMatrix4Translate(glkMatrix, x, y, z) } func multiply(left: Matrix4) { glkMatrix = GLKMatrix4Multiply(left.glkMatrix, glkMatrix) } var raw: [Float] { let value = glkMatrix.m //I cannot think of a better way of doing this return [value.0, value.1, value.2, value.3, value.4, value.5, value.6, value.7, value.8, value.9, value.10, value.11, value.12, value.13, value.14, value.15] } func transpose() { glkMatrix = GLKMatrix4Transpose(glkMatrix) } public static func *(lhs: Matrix4, rhs: Matrix4) -> Matrix4 { let m = Matrix4.identity m.glkMatrix.m00 = lhs.glkMatrix.m00 * rhs.glkMatrix.m00 + lhs.glkMatrix.m10 * rhs.glkMatrix.m01 + lhs.glkMatrix.m20 * rhs.glkMatrix.m02 + lhs.glkMatrix.m30 * rhs.glkMatrix.m03 m.glkMatrix.m01 = lhs.glkMatrix.m01 * rhs.glkMatrix.m00 + lhs.glkMatrix.m11 * rhs.glkMatrix.m01 + lhs.glkMatrix.m21 * rhs.glkMatrix.m02 + lhs.glkMatrix.m31 * rhs.glkMatrix.m03 m.glkMatrix.m02 = lhs.glkMatrix.m02 * rhs.glkMatrix.m00 + lhs.glkMatrix.m12 * rhs.glkMatrix.m01 + lhs.glkMatrix.m22 * rhs.glkMatrix.m02 + lhs.glkMatrix.m32 * rhs.glkMatrix.m03 m.glkMatrix.m03 = lhs.glkMatrix.m03 * rhs.glkMatrix.m00 + lhs.glkMatrix.m13 * rhs.glkMatrix.m01 + lhs.glkMatrix.m23 * rhs.glkMatrix.m02 + lhs.glkMatrix.m33 * rhs.glkMatrix.m03 m.glkMatrix.m10 = lhs.glkMatrix.m00 * rhs.glkMatrix.m10 + lhs.glkMatrix.m10 * rhs.glkMatrix.m11 + lhs.glkMatrix.m20 * rhs.glkMatrix.m12 + lhs.glkMatrix.m30 * rhs.glkMatrix.m13 m.glkMatrix.m11 = lhs.glkMatrix.m01 * rhs.glkMatrix.m10 + lhs.glkMatrix.m11 * rhs.glkMatrix.m11 + lhs.glkMatrix.m21 * rhs.glkMatrix.m12 + lhs.glkMatrix.m31 * rhs.glkMatrix.m13 m.glkMatrix.m12 = lhs.glkMatrix.m02 * rhs.glkMatrix.m10 + lhs.glkMatrix.m12 * rhs.glkMatrix.m11 + lhs.glkMatrix.m22 * rhs.glkMatrix.m12 + lhs.glkMatrix.m32 * rhs.glkMatrix.m13 m.glkMatrix.m13 = lhs.glkMatrix.m03 * rhs.glkMatrix.m10 + lhs.glkMatrix.m13 * rhs.glkMatrix.m11 + lhs.glkMatrix.m23 * rhs.glkMatrix.m12 + lhs.glkMatrix.m33 * rhs.glkMatrix.m13 m.glkMatrix.m20 = lhs.glkMatrix.m00 * rhs.glkMatrix.m20 + lhs.glkMatrix.m10 * rhs.glkMatrix.m21 + lhs.glkMatrix.m20 * rhs.glkMatrix.m22 + lhs.glkMatrix.m30 * rhs.glkMatrix.m23 m.glkMatrix.m21 = lhs.glkMatrix.m01 * rhs.glkMatrix.m20 + lhs.glkMatrix.m11 * rhs.glkMatrix.m21 + lhs.glkMatrix.m21 * rhs.glkMatrix.m22 + lhs.glkMatrix.m31 * rhs.glkMatrix.m23 m.glkMatrix.m22 = lhs.glkMatrix.m02 * rhs.glkMatrix.m20 + lhs.glkMatrix.m12 * rhs.glkMatrix.m21 + lhs.glkMatrix.m22 * rhs.glkMatrix.m22 + lhs.glkMatrix.m32 * rhs.glkMatrix.m23 m.glkMatrix.m23 = lhs.glkMatrix.m03 * rhs.glkMatrix.m20 + lhs.glkMatrix.m13 * rhs.glkMatrix.m21 + lhs.glkMatrix.m23 * rhs.glkMatrix.m22 + lhs.glkMatrix.m33 * rhs.glkMatrix.m23 m.glkMatrix.m30 = lhs.glkMatrix.m00 * rhs.glkMatrix.m30 + lhs.glkMatrix.m10 * rhs.glkMatrix.m31 + lhs.glkMatrix.m20 * rhs.glkMatrix.m32 + lhs.glkMatrix.m30 * rhs.glkMatrix.m33 m.glkMatrix.m31 = lhs.glkMatrix.m01 * rhs.glkMatrix.m30 + lhs.glkMatrix.m11 * rhs.glkMatrix.m31 + lhs.glkMatrix.m21 * rhs.glkMatrix.m32 + lhs.glkMatrix.m31 * rhs.glkMatrix.m33 m.glkMatrix.m32 = lhs.glkMatrix.m02 * rhs.glkMatrix.m30 + lhs.glkMatrix.m12 * rhs.glkMatrix.m31 + lhs.glkMatrix.m22 * rhs.glkMatrix.m32 + lhs.glkMatrix.m32 * rhs.glkMatrix.m33 m.glkMatrix.m33 = lhs.glkMatrix.m03 * rhs.glkMatrix.m30 + lhs.glkMatrix.m13 * rhs.glkMatrix.m31 + lhs.glkMatrix.m23 * rhs.glkMatrix.m32 + lhs.glkMatrix.m33 * rhs.glkMatrix.m33 return m } }
207a495c92da157fe0e50e8e8accd2ce
52.07767
183
0.648436
false
false
false
false
Wolkabout/WolkSense-Hexiwear-
refs/heads/master
iOS/Hexiwear/DataStore.swift
gpl-3.0
1
// // Hexiwear application is used to pair with Hexiwear BLE devices // and send sensor readings to WolkSense sensor data cloud // // Copyright (C) 2016 WolkAbout Technology s.r.o. // // Hexiwear 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. // // Hexiwear is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // // // DataStore.swift // import Foundation class DataStore { let webApi: WebAPI fileprivate let userCredentials: UserCredentials fileprivate let trackingDevice: TrackingDevice let concurrentDataStoreQueue = DispatchQueue(label: "com.wolkabout.DataStoreQueue", attributes: []) // synchronizes access to DataStore properties init(webApi: WebAPI, userCredentials: UserCredentials, trackingDevice: TrackingDevice) { self.webApi = webApi self.userCredentials = userCredentials self.trackingDevice = trackingDevice } func clearDataStore() { self.pointFeeds = [] self.points = [] } //MARK:- Properties fileprivate var _points: [Device] = [] var points: [Device] { get { var pointsCopy: [Device]! concurrentDataStoreQueue.sync { pointsCopy = self._points } return pointsCopy } set (newPoints) { self.concurrentDataStoreQueue.sync(flags: .barrier, execute: { // devices self._points = newPoints // feeds var feeds = [Feed]() for point in newPoints { if let enabledFeeds = point.enabledFeeds() { feeds += enabledFeeds } } self._pointFeeds = feeds }) } } // CURRENT DEVICE POINT fileprivate var _currentDevicePoint: Device? var currentDevicePoint: Device? { get { var pointCopy: Device? concurrentDataStoreQueue.sync { pointCopy = self._currentDevicePoint } return pointCopy } } // FEEDS fileprivate var _pointFeeds: [Feed] = [] var pointFeeds: [Feed] { get { var pointFeedsCopy: [Feed] = [] concurrentDataStoreQueue.sync { pointFeedsCopy = self._pointFeeds } return pointFeedsCopy } set (newPointFeeds) { self.concurrentDataStoreQueue.sync(flags: .barrier, execute: { self._pointFeeds = newPointFeeds }) } } func getDeviceNameForSerial(_ serial: String) -> String? { for point in self.points { if point.deviceSerial == serial { return point.name } } return nil } } //MARK:- Fetch points and fetch all (points + messages) extension DataStore { // FETCH ALL internal func fetchAll(_ onFailure: @escaping (Reason) -> (), onSuccess: @escaping () -> ()) { // POINTS webApi.fetchPoints(onFailure) { dev in self.points = dev onSuccess() } } } //MARK:- Device management extension DataStore { // GET ACTIVATION STATUS for serial func getActivationStatusForSerial(_ serial: String, onFailure: @escaping (Reason) -> (), onSuccess: @escaping (_ activationStatus: String) -> ()) { // Check precondition guard !serial.isEmpty else { onSuccess("NOT_ACTIVATED") return } webApi.getDeviceActivationStatus(serial, onFailure: onFailure, onSuccess: onSuccess) } // GET RANDOM SERIAL func getSerial(_ onFailure: @escaping (Reason) -> (), onSuccess: @escaping (_ serial: String) -> ()) { webApi.getRandomSerial(onFailure, onSuccess:onSuccess) } // ACTIVATE internal func activateDeviceWithSerialAndName(_ deviceSerial: String, deviceName: String, onFailure: @escaping (Reason) -> (), onSuccess: @escaping (_ pointId: Int, _ password: String) -> ()) { // Check precondition guard !deviceSerial.isEmpty && !deviceName.isEmpty else { onFailure(.noData) return } webApi.activateDevice(deviceSerial, deviceName: deviceName, onFailure: onFailure, onSuccess: onSuccess) } // DEACTIVATE internal func deactivateDevice(_ serialNumber: String, onFailure: @escaping (Reason) -> (), onSuccess: @escaping () -> ()) { // Check precondition guard !serialNumber.isEmpty else { onFailure(.noData) return } webApi.deactivateDevice(serialNumber, onFailure: onFailure, onSuccess: onSuccess) } } //MARK:- User account management extension DataStore { // SIGN UP internal func signUpWithAccount(_ account: Account, onFailure: @escaping (Reason) -> (), onSuccess: @escaping () -> ()) { webApi.signUp(account.firstName, lastName: account.lastName, email: account.email, password: account.password, onFailure: onFailure, onSuccess: onSuccess) } // SIGN IN internal func signInWithUsername(_ username: String, password: String, onFailure: @escaping (Reason) -> (), onSuccess: @escaping () -> ()) { webApi.signIn(username, password: password, onFailure: onFailure, onSuccess: onSuccess) } // RESET PASSWORD internal func resetPasswordForUserEmail(_ userEmail: String, onFailure: @escaping (Reason) -> (), onSuccess: @escaping () -> ()) { webApi.resetPassword(userEmail, onFailure: onFailure, onSuccess: onSuccess) } // CHANGE PASSWORD internal func changePasswordForUserEmail(oldPassword: String, newPassword:String, onFailure: @escaping (Reason) -> (), onSuccess: @escaping () -> ()) { webApi.changePassword(oldPassword: oldPassword, newPassword: newPassword, onFailure: onFailure, onSuccess: onSuccess) } }
2bb75f0c8c14daa546880134b429ae7e
32.443878
200
0.603509
false
false
false
false
Byjuanamn/AzureStorageMobileiOS
refs/heads/master
Azure/Storage/MyVideoBlog/MyVideoBlog/ContainersTableController.swift
mit
1
import UIKit class ContainersTableController: UITableViewController { let account = AZSCloudStorageAccount(fromConnectionString: "DefaultEndpointsProtocol=https;AccountName=videoblogapp;AccountKey=MaRn1e2rvWYZh+zzlbMZVoHiikmNNCrzT6Gjvixh4Thtj4Wv2DfTxbR1Ab+PAvixt5r5nCt0SBCX8LdbYrLhYA==") var model : [AZSCloudBlobContainer]? override func viewDidLoad() { super.viewDidLoad() populateModel() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Azure Storage Containers Model func populateModel(){ let blobClient : AZSCloudBlobClient = account.getBlobClient() blobClient.listContainersSegmentedWithContinuationToken(nil) { (error : NSError?, resultSegment : AZSContainerResultSegment?) -> Void in if (error == nil){ self.model = resultSegment?.results as? [AZSCloudBlobContainer] dispatch_async(dispatch_get_main_queue(), { () -> Void in self.tableView.reloadData() }) } } } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { var rows = 0 if let model = model { rows = model.count } return rows } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("celdaContainer", forIndexPath: indexPath) let contendor : AZSCloudBlobContainer = model![indexPath.row] cell.textLabel?.text = contendor.name return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { performSegueWithIdentifier("containerDetail", sender: indexPath) } // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if (segue.identifier == "containerDetail"){ let vc = segue.destinationViewController as? DetailContainerTableController let index = sender as! NSIndexPath vc?.currentContainer = model![index.row] } } }
3b6654c52f501ed029d5a78ca772d653
25.105769
221
0.634254
false
false
false
false
IvanVorobei/RateApp
refs/heads/master
SPRateApp - project/SPRateApp/sparrow/ui/views/views/SPShadowWithMaskView.swift
mit
1
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([email protected]) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit public class SPShadowWithMaskView<ContentView: UIView>: UIView { public let contentView: ContentView = ContentView() public init() { super.init(frame: CGRect.zero) commonInit() } override public init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { self.contentView.layer.masksToBounds = true self.layer.masksToBounds = false self.contentView.layer.masksToBounds = true self.backgroundColor = UIColor.clear self.addSubview(contentView) self.updateShadow() } public override func layoutSubviews() { super.layoutSubviews() self.contentView.frame = self.bounds self.layer.cornerRadius = self.contentView.layer.cornerRadius } public override func layoutSublayers(of layer: CALayer) { super.layoutSublayers(of: layer) self.updateShadow() } private var xTranslationFactor: CGFloat = 0 private var yTranslationFactor: CGFloat = 0 private var widthRelativeFactor: CGFloat = 0 private var heightRelativeFactor: CGFloat = 0 private var blurRadiusFactor: CGFloat = 0 private var shadowOpacity: CGFloat = 0 public override func setShadow(xTranslationFactor: CGFloat, yTranslationFactor: CGFloat, widthRelativeFactor: CGFloat, heightRelativeFactor: CGFloat, blurRadiusFactor: CGFloat, shadowOpacity: CGFloat, cornerRadiusFactor: CGFloat = 0) { super.setShadow(xTranslationFactor: xTranslationFactor, yTranslationFactor: yTranslationFactor, widthRelativeFactor: widthRelativeFactor, heightRelativeFactor: heightRelativeFactor, blurRadiusFactor: blurRadiusFactor, shadowOpacity: shadowOpacity, cornerRadiusFactor: cornerRadiusFactor) self.xTranslationFactor = xTranslationFactor self.yTranslationFactor = yTranslationFactor self.widthRelativeFactor = widthRelativeFactor self.heightRelativeFactor = heightRelativeFactor self.blurRadiusFactor = blurRadiusFactor self.shadowOpacity = shadowOpacity } private func updateShadow() { self.setShadow( xTranslationFactor: self.xTranslationFactor, yTranslationFactor: self.yTranslationFactor, widthRelativeFactor: self.widthRelativeFactor, heightRelativeFactor: self.heightRelativeFactor, blurRadiusFactor: self.blurRadiusFactor, shadowOpacity: self.shadowOpacity ) } } public class SPShadowWithMaskControl: UIControl { public let contentView: UIView = UIView() public init() { super.init(frame: CGRect.zero) commonInit() } override public init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { self.contentView.layer.masksToBounds = true self.layer.masksToBounds = false self.backgroundColor = UIColor.clear self.addSubview(contentView) self.updateShadow() } public override func layoutSubviews() { super.layoutSubviews() self.contentView.frame = self.bounds self.layer.cornerRadius = self.contentView.layer.cornerRadius } public override func layoutSublayers(of layer: CALayer) { super.layoutSublayers(of: layer) self.updateShadow() } private var xTranslationFactor: CGFloat = 0 private var yTranslationFactor: CGFloat = 0 private var widthRelativeFactor: CGFloat = 0 private var heightRelativeFactor: CGFloat = 0 private var blurRadiusFactor: CGFloat = 0 private var shadowOpacity: CGFloat = 0 public override func setShadow(xTranslationFactor: CGFloat, yTranslationFactor: CGFloat, widthRelativeFactor: CGFloat, heightRelativeFactor: CGFloat, blurRadiusFactor: CGFloat, shadowOpacity: CGFloat, cornerRadiusFactor: CGFloat = 0) { super.setShadow(xTranslationFactor: xTranslationFactor, yTranslationFactor: yTranslationFactor, widthRelativeFactor: widthRelativeFactor, heightRelativeFactor: heightRelativeFactor, blurRadiusFactor: blurRadiusFactor, shadowOpacity: shadowOpacity, cornerRadiusFactor: cornerRadiusFactor) self.xTranslationFactor = xTranslationFactor self.yTranslationFactor = yTranslationFactor self.widthRelativeFactor = widthRelativeFactor self.heightRelativeFactor = heightRelativeFactor self.blurRadiusFactor = blurRadiusFactor self.shadowOpacity = shadowOpacity } private func updateShadow() { self.setShadow( xTranslationFactor: self.xTranslationFactor, yTranslationFactor: self.yTranslationFactor, widthRelativeFactor: self.widthRelativeFactor, heightRelativeFactor: self.heightRelativeFactor, blurRadiusFactor: self.blurRadiusFactor, shadowOpacity: self.shadowOpacity ) } }
d7e2e8878d384fbc10542bfb9caf4efc
39.681529
295
0.711915
false
false
false
false
welbesw/dicom-data-view
refs/heads/master
DicomDataView/DicomDataView/PixelDataViewController.swift
gpl-2.0
1
// // PixelDataViewController.swift // DicomDataView // // Created by William Welbes on 4/6/16. // Copyright © 2016 Technomagination, LLC. All rights reserved. // import Cocoa class PixelDataViewController: NSViewController { var dicomObject: DCMObject? = nil @IBOutlet var imageView:NSImageView! override func viewDidLoad() { super.viewDidLoad() // Do view setup here. } override func viewWillAppear() { super.viewWillAppear() loadDicomFile() //The document is not yet set in viewDidLoad } func loadDicomFile() { if let windowController = NSApplication.sharedApplication().mainWindow?.windowController { if let document = windowController.document as? Document { self.dicomObject = document.dicomObject loadPixelData() } } } func loadPixelData() { if let dcmObject = self.dicomObject { if let dcmPixelDataAttribute = dcmObject.attributes["7FE0,0010"] as? DCMPixelDataAttribute { if dcmPixelDataAttribute.numberOfFrames > 0 { let frameData = dcmPixelDataAttribute.decodeFrameAtIndex(0) if let image = NSImage(data: frameData) { imageView.image = image; } } } } } }
23d1326c86f7d1fe2ea8bb3b7254348a
25.722222
104
0.572419
false
false
false
false
yunzixun/V2ex-Swift
refs/heads/master
View/FontSizeSliderTableViewCell.swift
mit
1
// // FontSizeSliderTableViewCell.swift // V2ex-Swift // // Created by huangfeng on 3/10/16. // Copyright © 2016 Fin. All rights reserved. // import UIKit class FontSizeSliderTableViewCell: UITableViewCell { override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier); self.setup(); } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } func setup() { self.selectionStyle = .none let leftLabel = UILabel() leftLabel.font = v2Font(14 * 0.8) leftLabel.text = "A" leftLabel.textAlignment = .center self.contentView.addSubview(leftLabel) leftLabel.snp.makeConstraints{ (make) -> Void in make.centerY.equalTo(self.contentView) make.width.height.equalTo(30) make.left.equalTo(self.contentView) } let rightLabel = UILabel() rightLabel.font = v2Font(14 * 1.6) rightLabel.text = "A" rightLabel.textAlignment = .center self.contentView.addSubview(rightLabel) rightLabel.snp.makeConstraints{ (make) -> Void in make.centerY.equalTo(self.contentView) make.width.height.equalTo(30) make.right.equalTo(self.contentView) } let slider = V2Slider() slider.valueChanged = { (fontSize) in let size = fontSize * 0.05 + 0.8 if V2Style.sharedInstance.fontScale != size { V2Style.sharedInstance.fontScale = size } } self.contentView.addSubview(slider) slider.snp.makeConstraints{ (make) -> Void in make.left.equalTo(leftLabel.snp.right) make.right.equalTo(rightLabel.snp.left) make.centerY.equalTo(self.contentView) } let topSeparator = UIImageView() self.contentView.addSubview(topSeparator) topSeparator.snp.makeConstraints{ (make) -> Void in make.left.right.top.equalTo(self.contentView) make.height.equalTo(SEPARATOR_HEIGHT) } let bottomSeparator = UIImageView() self.contentView.addSubview(bottomSeparator) bottomSeparator.snp.makeConstraints{ (make) -> Void in make.left.right.bottom.equalTo(self.contentView) make.height.equalTo(SEPARATOR_HEIGHT) } self.themeChangedHandler = {[weak self] (style) -> Void in self?.backgroundColor = V2EXColor.colors.v2_CellWhiteBackgroundColor leftLabel.textColor = V2EXColor.colors.v2_TopicListTitleColor rightLabel.textColor = V2EXColor.colors.v2_TopicListTitleColor topSeparator.image = createImageWithColor( V2EXColor.colors.v2_SeparatorColor ) bottomSeparator.image = topSeparator.image } } }
9fb3077ffa8752dc66fa1c2f1b6168c3
35.160494
91
0.621714
false
false
false
false
mcxiaoke/learning-ios
refs/heads/master
ios_programming_4th/Hypnosister-ch5/Hypnosister/HypnosisterView.swift
apache-2.0
1
// // HypnosisterView.swift // Hypnosister // // Created by Xiaoke Zhang on 2017/8/15. // Copyright © 2017年 Xiaoke Zhang. All rights reserved. // import UIKit class HypnosisterView: UIView { var circleColor = UIColor.lightGray { didSet { setNeedsDisplay() } } override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clear } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func draw(_ rect: CGRect) { let bounds = self.bounds var center = CGPoint() center.x = bounds.origin.x + bounds.size.width/2.0; center.y = bounds.origin.y + bounds.size.height/2.0; let maxRadius = hypot(bounds.size.width, bounds.size.height)/2.0; let path = UIBezierPath() var currentRadius = maxRadius while currentRadius>0 { path.move(to: CGPoint(x:center.x+currentRadius, y:center.y)) path.addArc(withCenter: center, radius: currentRadius, startAngle: 0.0, endAngle: CGFloat(Double.pi*2), clockwise: true) currentRadius -= 20 } path.lineWidth = 10 circleColor.setStroke() path.stroke() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { let red = CGFloat(arc4random_uniform(100))/100.0 let green = CGFloat(arc4random_uniform(100))/100.0 let blue = CGFloat(arc4random_uniform(100))/100.0 let color = UIColor(red:red, green:green, blue:blue, alpha:1.0) self.circleColor = color print("touchesBegan color=\(color.toHex)") } }
879df869a01e33936240652fad69bda5
28.688525
79
0.571507
false
false
false
false
lucasharding/antenna
refs/heads/master
tvOS/Controllers/PlayerViewController.swift
gpl-3.0
1
// // PlayerViewController.swift // ustvnow-tvos // // Created by Lucas Harding on 2015-09-11. // Copyright © 2015 Lucas Harding. All rights reserved. // import UIKit import AVFoundation import Alamofire //MARK: - PlayerViewController open class PlayerViewController : UIViewController, UIGestureRecognizerDelegate { @IBOutlet var activityIndicator: UIActivityIndicatorView! @IBOutlet var playerView: PlayerLayerWrapperView? var activityTimer: Timer? { didSet { oldValue?.invalidate() } } lazy var upgradeViewController: PlayerUpgradeViewController = { let controller = self.storyboard!.instantiateViewController(withIdentifier: "PlayerUpgrade") as! PlayerUpgradeViewController controller.view.frame = self.view.frame self.view.addSubview(controller.view) self.addChildViewController(controller) return controller }() lazy var overlayViewController: PlayerOverlayViewController = { let controller = self.storyboard!.instantiateViewController(withIdentifier: "PlayerOverlay") as! PlayerOverlayViewController controller.view.frame = self.view.frame self.addChildViewController(controller) self.view.addSubview(controller.view) return controller }() open var player: AVPlayer? { didSet { self.playerView?.player = self.player } } open var channel: TVChannel? { didSet { self.view.isHidden = false self.overlayViewController.channel = self.channel if let channel = self.channel { self.upgradeViewController.imageView.image = UIImage(named: channel.guideImageString) self.upgradeViewController.titleLabel.text = "\(channel.name) is unavailable" self.upgradeViewController.view.isHidden = channel.available if channel.available { if channel.streamName != oldValue?.streamName { TVService.sharedInstance.playChannel(channel) { url in if let url = url { let asset = AVURLAsset(url: url, options: ["AVURLAssetHTTPHeaderFieldsKey": [ "User-Agent": TVService.sharedInstance.randomUserAgent, "X-Playback-Session-Id": UUID().uuidString, ]]) self.player = AVPlayer(playerItem: AVPlayerItem(asset: asset)) self.player?.play() } else { self.player = nil } } } } else { self.player = nil } } else { self.player = nil } } } override open var preferredFocusedView: UIView? { get { return self.overlayViewController.view } } //MARK: View open override func viewDidLoad() { super.viewDidLoad() self.view.addSubview(self.upgradeViewController.view) self.view.addSubview(self.overlayViewController.view) let playTapRecognizer = UITapGestureRecognizer(target: self, action:#selector(PlayerViewController.didPressPlay(_:))) playTapRecognizer.allowedPressTypes = [NSNumber(value: UIPressType.playPause.rawValue as Int)]; self.view.addGestureRecognizer(playTapRecognizer) } open override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) self.activityTimer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(PlayerViewController.activityTimerTick), userInfo: nil, repeats: true) self.showOverlay() } open override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) self.activityTimer = nil } //MARK: Other func didPressPlay(_ recognizer: UITapGestureRecognizer) { self.player?.rate = self.player?.rate == 1 ? 0.0 : 1.0 } fileprivate func showOverlay() { self.view.isHidden = false self.overlayViewController.channels = TVService.sharedInstance.guide?.channels self.overlayViewController.updateWith(self.channel) self.overlayViewController.setPanOffset(self.overlayViewController.panOffsetThreshold) self.overlayViewController.overlayTimer = Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(PlayerViewController.hideOverlay), userInfo: nil, repeats: false) } @objc fileprivate func hideOverlay() { self.overlayViewController.setPanOffset(0, animated: true) } @objc fileprivate func activityTimerTick() { if (self.player == nil || (self.player?.currentItem?.loadedTimeRanges.count ?? 0) > 0 && self.player?.currentItem?.isPlaybackLikelyToKeepUp == true) { activityIndicator.stopAnimating() } else { activityIndicator.startAnimating() } } } class PlayerLayerWrapperView: UIView { var playerLayer: AVPlayerLayer? var player: AVPlayer? { get { return self.playerLayer?.player } set { self.playerLayer?.player = newValue } } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.playerLayer = AVPlayerLayer() self.layer.addSublayer(self.playerLayer!) } override func layoutSubviews() { super.layoutSubviews() self.playerLayer?.frame = self.bounds } }
de7cb2053b0f667e69fc70c1bd3aa44e
34.89441
187
0.611698
false
false
false
false
SummerHanada/CollectionViewWaterfallLayout
refs/heads/master
CollectionViewWaterfallLayout.swift
mit
5
// // CollectionViewWaterfallLayout.swift // CollectionViewWaterfallLayout // // Created by Eric Cerney on 7/21/14. // Based on CHTCollectionViewWaterfallLayout by Nelson Tai // Copyright (c) 2014 Eric Cerney. All rights reserved. // import UIKit public let CollectionViewWaterfallElementKindSectionHeader = "CollectionViewWaterfallElementKindSectionHeader" public let CollectionViewWaterfallElementKindSectionFooter = "CollectionViewWaterfallElementKindSectionFooter" @objc public protocol CollectionViewWaterfallLayoutDelegate:UICollectionViewDelegate { func collectionView(collectionView: UICollectionView, layout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize optional func collectionView(collectionView: UICollectionView, layout: UICollectionViewLayout, heightForHeaderInSection section: Int) -> Float optional func collectionView(collectionView: UICollectionView, layout: UICollectionViewLayout, heightForFooterInSection section: Int) -> Float optional func collectionView(collectionView: UICollectionView, layout: UICollectionViewLayout, insetForSection section: Int) -> UIEdgeInsets optional func collectionView(collectionView: UICollectionView, layout: UICollectionViewLayout, insetForHeaderInSection section: Int) -> UIEdgeInsets optional func collectionView(collectionView: UICollectionView, layout: UICollectionViewLayout, insetForFooterInSection section: Int) -> UIEdgeInsets optional func collectionView(collectionView: UICollectionView, layout: UICollectionViewLayout, minimumInteritemSpacingForSection section: Int) -> Float } public class CollectionViewWaterfallLayout: UICollectionViewLayout { //MARK: Private constants /// How many items to be union into a single rectangle private let unionSize = 20; //MARK: Public Properties public var columnCount:Int = 2 { didSet { invalidateIfNotEqual(oldValue, newValue: columnCount) } } public var minimumColumnSpacing:Float = 10.0 { didSet { invalidateIfNotEqual(oldValue, newValue: minimumColumnSpacing) } } public var minimumInteritemSpacing:Float = 10.0 { didSet { invalidateIfNotEqual(oldValue, newValue: minimumInteritemSpacing) } } public var headerHeight:Float = 0.0 { didSet { invalidateIfNotEqual(oldValue, newValue: headerHeight) } } public var footerHeight:Float = 0.0 { didSet { invalidateIfNotEqual(oldValue, newValue: footerHeight) } } public var headerInset:UIEdgeInsets = UIEdgeInsetsZero { didSet { invalidateIfNotEqual(NSValue(UIEdgeInsets: oldValue), newValue: NSValue(UIEdgeInsets: headerInset)) } } public var footerInset:UIEdgeInsets = UIEdgeInsetsZero { didSet { invalidateIfNotEqual(NSValue(UIEdgeInsets: oldValue), newValue: NSValue(UIEdgeInsets: footerInset)) } } public var sectionInset:UIEdgeInsets = UIEdgeInsetsZero { didSet { invalidateIfNotEqual(NSValue(UIEdgeInsets: oldValue), newValue: NSValue(UIEdgeInsets: sectionInset)) } } //MARK: Private Properties private weak var delegate: CollectionViewWaterfallLayoutDelegate? { get { return collectionView?.delegate as? CollectionViewWaterfallLayoutDelegate } } private var columnHeights = [Float]() private var sectionItemAttributes = [[UICollectionViewLayoutAttributes]]() private var allItemAttributes = [UICollectionViewLayoutAttributes]() private var headersAttribute = [Int: UICollectionViewLayoutAttributes]() private var footersAttribute = [Int: UICollectionViewLayoutAttributes]() private var unionRects = [CGRect]() //MARK: UICollectionViewLayout Methods override public func prepareLayout() { super.prepareLayout() let numberOfSections = collectionView?.numberOfSections() if numberOfSections == 0 { return; } assert(delegate!.conformsToProtocol(CollectionViewWaterfallLayoutDelegate), "UICollectionView's delegate should conform to WaterfallLayoutDelegate protocol") assert(columnCount > 0, "WaterfallFlowLayout's columnCount should be greater than 0") // Initialize variables headersAttribute.removeAll(keepCapacity: false) footersAttribute.removeAll(keepCapacity: false) unionRects.removeAll(keepCapacity: false) columnHeights.removeAll(keepCapacity: false) allItemAttributes.removeAll(keepCapacity: false) sectionItemAttributes.removeAll(keepCapacity: false) for idx in 0..<columnCount { self.columnHeights.append(0) } // Create attributes var top:Float = 0 var attributes: UICollectionViewLayoutAttributes for section in 0..<numberOfSections! { /* * 1. Get section-specific metrics (minimumInteritemSpacing, sectionInset) */ var minimumInteritemSpacing: Float if let height = delegate?.collectionView?(collectionView!, layout: self, minimumInteritemSpacingForSection: section) { minimumInteritemSpacing = height } else { minimumInteritemSpacing = self.minimumInteritemSpacing } var sectionInset: UIEdgeInsets if let inset = delegate?.collectionView?(collectionView!, layout: self, insetForSection: section) { sectionInset = inset } else { sectionInset = self.sectionInset } let width = Float(collectionView!.frame.size.width - sectionInset.left - sectionInset.right) let itemWidth = floorf((width - Float(columnCount - 1) * Float(minimumColumnSpacing)) / Float(columnCount)) /* * 2. Section header */ var headerHeight: Float if let height = delegate?.collectionView?(collectionView!, layout: self, heightForHeaderInSection: section) { headerHeight = height } else { headerHeight = self.headerHeight } var headerInset: UIEdgeInsets if let inset = delegate?.collectionView?(collectionView!, layout: self, insetForHeaderInSection: section) { headerInset = inset } else { headerInset = self.headerInset } top += Float(headerInset.top) if headerHeight > 0 { attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: CollectionViewWaterfallElementKindSectionHeader, withIndexPath: NSIndexPath(forItem: 0, inSection: section)) attributes.frame = CGRect(x: headerInset.left, y: CGFloat(top), width: collectionView!.frame.size.width - (headerInset.left + headerInset.right), height: CGFloat(headerHeight)) headersAttribute[section] = attributes allItemAttributes.append(attributes) top = Float(CGRectGetMaxY(attributes.frame)) + Float(headerInset.bottom) } top += Float(sectionInset.top) for idx in 0..<columnCount { columnHeights[idx] = top } /* * 3. Section items */ let itemCount = collectionView!.numberOfItemsInSection(section) var itemAttributes = [UICollectionViewLayoutAttributes]() // Item will be put into shortest column. for idx in 0..<itemCount { let indexPath = NSIndexPath(forItem: idx, inSection: section) let columnIndex = shortestColumnIndex() let xOffset = Float(sectionInset.left) + Float(itemWidth + minimumColumnSpacing) * Float(columnIndex) let yOffset = columnHeights[columnIndex] let itemSize = delegate?.collectionView(collectionView!, layout: self, sizeForItemAtIndexPath: indexPath) var itemHeight: Float = 0.0 if itemSize?.height > 0 && itemSize?.width > 0 { itemHeight = Float(itemSize!.height) * itemWidth / Float(itemSize!.width) } attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath) attributes.frame = CGRect(x: CGFloat(xOffset), y: CGFloat(yOffset), width: CGFloat(itemWidth), height: CGFloat(itemHeight)) itemAttributes.append(attributes) allItemAttributes.append(attributes) columnHeights[columnIndex] = Float(CGRectGetMaxY(attributes.frame)) + minimumInteritemSpacing } sectionItemAttributes.append(itemAttributes) /* * 4. Section footer */ var footerHeight: Float var columnIndex = longestColumnIndex() top = columnHeights[columnIndex] - minimumInteritemSpacing + Float(sectionInset.bottom) if let height = delegate?.collectionView?(collectionView!, layout: self, heightForFooterInSection: section) { footerHeight = height } else { footerHeight = self.footerHeight } var footerInset: UIEdgeInsets if let inset = delegate?.collectionView?(collectionView!, layout: self, insetForFooterInSection: section) { footerInset = inset } else { footerInset = self.footerInset } top += Float(footerInset.top) if footerHeight > 0 { attributes = UICollectionViewLayoutAttributes(forSupplementaryViewOfKind: CollectionViewWaterfallElementKindSectionFooter, withIndexPath: NSIndexPath(forItem: 0, inSection: section)) attributes.frame = CGRect(x: footerInset.left, y: CGFloat(top), width: collectionView!.frame.size.width - (footerInset.left + footerInset.right), height: CGFloat(footerHeight)) footersAttribute[section] = attributes allItemAttributes.append(attributes) top = Float(CGRectGetMaxY(attributes.frame)) + Float(footerInset.bottom) } for idx in 0..<columnCount { columnHeights[idx] = top } } // Build union rects var idx = 0 let itemCounts = allItemAttributes.count while idx < itemCounts { let rect1 = allItemAttributes[idx].frame idx = min(idx + unionSize, itemCounts) - 1 let rect2 = allItemAttributes[idx].frame unionRects.append(CGRectUnion(rect1, rect2)) ++idx } } override public func collectionViewContentSize() -> CGSize { let numberOfSections = collectionView?.numberOfSections() if numberOfSections == 0 { return CGSizeZero } var contentSize = collectionView?.bounds.size contentSize?.height = CGFloat(columnHeights[0]) return contentSize! } override public func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { if indexPath.section >= sectionItemAttributes.count { return nil } if indexPath.item >= sectionItemAttributes[indexPath.section].count { return nil } return sectionItemAttributes[indexPath.section][indexPath.item] } override public func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes! { var attribute: UICollectionViewLayoutAttributes? if elementKind == CollectionViewWaterfallElementKindSectionHeader { attribute = headersAttribute[indexPath.section] } else if elementKind == CollectionViewWaterfallElementKindSectionFooter { attribute = footersAttribute[indexPath.section] } return attribute } override public func layoutAttributesForElementsInRect(rect: CGRect) -> [AnyObject] { var begin:Int = 0 var end: Int = unionRects.count var attrs = [UICollectionViewLayoutAttributes]() for i in 0..<unionRects.count { if CGRectIntersectsRect(rect, unionRects[i]) { begin = i * unionSize break } } for i in reverse(0..<unionRects.count) { if CGRectIntersectsRect(rect, unionRects[i]) { end = min((i+1) * unionSize, allItemAttributes.count) break } } for var i = begin; i < end; i++ { let attr = allItemAttributes[i] if CGRectIntersectsRect(rect, attr.frame) { attrs.append(attr) } } return Array(attrs) } override public func shouldInvalidateLayoutForBoundsChange(newBounds: CGRect) -> Bool { let oldBounds = collectionView?.bounds if CGRectGetWidth(newBounds) != CGRectGetWidth(oldBounds!) { return true } return false } //MARK: Private Methods private func shortestColumnIndex() -> Int { var index: Int = 0 var shortestHeight = MAXFLOAT for (idx, height) in enumerate(columnHeights) { if height < shortestHeight { shortestHeight = height index = idx } } return index } private func longestColumnIndex() -> Int { var index: Int = 0 var longestHeight:Float = 0 for (idx, height) in enumerate(columnHeights) { if height > longestHeight { longestHeight = height index = idx } } return index } private func invalidateIfNotEqual(oldValue: AnyObject, newValue: AnyObject) { if !oldValue.isEqual(newValue) { invalidateLayout() } } }
4f6ff410296c676760a8c8af8b5982cb
38.649596
198
0.617199
false
false
false
false
linweiqiang/WQDouShi
refs/heads/0331
WQDouShi/WQDouShi/Discover/Model/VideoListModel.swift
mit
1
// // VideoListModel.swift // WQDouShi // // Created by yoke2 on 2017/3/22. // Copyright © 2017年 yoke121. All rights reserved. // import UIKit class VideoListModel: NSObject { var title : String? var videoDescription: String? var videoUrl: String? //封面 var coverForFeed: String? var date: NSNumber? var playInfo: [VideoModel] = [VideoModel]() override init(){ super.init() } init(dict: [String: Any]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forKey key: String) { if key == "playInfo" { var models = [VideoModel]() for dict in value as! [[String: AnyObject]] { models.append(VideoModel(dict: dict)) } playInfo = models return } if key == "data" { date = value as! NSNumber? } super.setValue(value, forKey: key) } override func setValue(_ value: Any?, forUndefinedKey key: String) { if key == "description" { self.videoDescription = value as! String? } } }
b776fa91807508ccf54441dd773346d4
21.576923
72
0.536627
false
false
false
false
collegboi/Media-App-iOS
refs/heads/master
MoviePickerViewController.swift
mit
1
// // MoviePickerViewController.swift // Media Center // // Created by Timothy Barnard on 07/12/2015. // Copyright © 2015 Timothy Barnard. All rights reserved. // import UIKit class MoviePickerViewController: UIViewController { var movieArray = [Image]() var imageCount = 0; override func viewDidLoad() { super.viewDidLoad() self.urlToImage(movieArray[0].getImage()) print(movieArray.count) } func setUpImageViews() { } func urlToImage(urlString:String) { let imgURL = NSURL(string: urlString) let request: NSURLRequest = NSURLRequest(URL: imgURL!) let mainQueue = NSOperationQueue.mainQueue() NSURLConnection.sendAsynchronousRequest(request, queue: mainQueue, completionHandler: { (response, data, error) -> Void in if error == nil { // Convert the downloaded data in to a UIImage object let image = UIImage(data: data!) dispatch_async(dispatch_get_main_queue(), { self.movieImageView.image = image }) } }) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func goBack(sender: AnyObject) { self.navigationController?.popToRootViewControllerAnimated(true) } }
f961a36eba0d438b93a86e8a08956ea4
25.210526
130
0.592369
false
false
false
false
gs01md/ColorfulWoodUIUser
refs/heads/master
TestUI/Pods/LoginKit/LoginKit/Models/User.swift
mit
1
import Foundation import KeychainAccess public class User: NSObject, NSCoding { public let id: String let username: String var password: String? { didSet { if LoginService.storePassword && LoginKitConfig.authType == AuthType.Basic { // Store to keychain if password != nil { do { try keychain.set(password!, key: "password") } catch { NSLog("Failed to set password") } } else { self.clearPassword() } } } } let keychain = Keychain(service: NSBundle.mainBundle().bundleIdentifier ?? "com.loginkit.keychain") var authToken: String? { didSet { if LoginService.storePassword { // Store to keychain if LoginKitConfig.authType == AuthType.JWT { if authToken != nil { do { try keychain.set(authToken!, key: "authToken") } catch { NSLog("Failed to set authToken") } } else { self.clearToken() } } } } } func clearToken() { do { try keychain.remove("authToken") } catch { NSLog("Failed to clear authToken") } } func clearPassword() { do { try keychain.remove("password") } catch { NSLog("Failed to clear password") } } init(id: String, username: String) { self.id = id self.username = username } public required init(coder aDecoder: NSCoder) { if let username = aDecoder.decodeObjectForKey("username") as? String, let id = aDecoder.decodeObjectForKey("id") as? String { self.id = id self.username = username } else { self.id = "" self.username = "" } do { if let password = try keychain.get("password") { self.password = password } } catch { NSLog("Failed to set password") } if (LoginKitConfig.savedLogin == false){ do { if let authToken = try keychain.get("authToken") { self.authToken = authToken } } catch { NSLog("Failed to set authToken") } } } public func encodeWithCoder(aCoder: NSCoder) { aCoder.encodeObject(self.id, forKey: "id") aCoder.encodeObject(self.username, forKey: "username") if let authToken = self.authToken { aCoder.encodeObject(authToken, forKey: "authToken") } } }
7a8112a766bc839e01e94b728b6ec400
26.564815
103
0.455492
false
false
false
false
TonyJin99/SinaWeibo
refs/heads/master
SinaWeibo/SinaWeibo/TJTextView.swift
apache-2.0
1
// // TJTextView.swift // SinaWeibo // // Created by Tony.Jin on 8/16/16. // Copyright © 2016 Innovatis Tech. All rights reserved. // import UIKit import SnapKit class TJTextView: UITextView { override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) setupUI() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupUI() } private func setupUI(){ addSubview(placeholderLabel) placeholderLabel.snp_makeConstraints { (make) in make.left.equalTo(4) make.top.equalTo(8) } NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(valueChange), name: UITextViewTextDidChangeNotification, object: self) } deinit{ NSNotificationCenter.defaultCenter().removeObserver(self) } func valueChange(){ placeholderLabel.hidden = hasText() } private lazy var placeholderLabel: UILabel = { let lb = UILabel() lb.text = "分享新鲜事..." lb.textColor = UIColor.lightGrayColor() return lb }() }
194ef71a790528c6697bc0246a73d371
22.056604
153
0.60802
false
false
false
false
Jerrywx/Swift_Down
refs/heads/master
Headers/Swift Guide.playground/Pages/Extensions(扩展).xcplaygroundpage/Contents.swift
apache-2.0
2
//: [Previous](@previous) import Foundation //: 1. 扩展语法 //: 2. 计算属性 /*: 计算型实例属性 */ // 计算性类型属性 //: 3.构造器 /// Size struct Size { var width = 0.0, height = 0.0 } /// Point struct Point { var x = 0.0, y = 0.0 } /// Rect struct Rect { var size = Size(width: 0.0, height: 0.0) var origin = Point(x: 0.0, y: 0.0) } let size = Size(width: 100, height: 100) let point = Point(x: 20, y: 20) let rect = Rect(size: size, origin: point) /// 扩展构造方法 extension Rect { init(center:Point, size: Size) { let x = center.x - size.width * 0.5 let y = center.y - size.height * 0.5 self.init(size: size, origin: Point(x:x, y:y)) } } let rec = Rect(center: Point(x:200, y:200), size: Size(width: 100, height: 100)) print(rec) //: 4. 方法 // extension Int { /// 执行多次 func repetitions(){ for _ in 0..<self { print("-----") } } /// 多次执行特定代码 func repetitions2(task: ()->()) { for _ in 0..<self { task() } } /// 立方操作 mutating func square() { self = self * self } } /// 3.repetitions() 4.repetitions2 { print("......") } var numb = 6 numb.square() //: 5. 小标 //: 6. 嵌套类型 //: [Next](@next)
f24927ef0a7e5242eba6bd9377bdac4c
9.923077
80
0.548415
false
false
false
false
HabitRPG/habitrpg-ios
refs/heads/develop
HabitRPG/TableViewDataSources/HallOfContributorsDataSource.swift
gpl-3.0
1
// // HallOfContributorsDataSource.swift // Habitica // // Created by Phillip Thelen on 11.08.20. // Copyright © 2020 HabitRPG Inc. All rights reserved. // import Foundation import Habitica_Models class HallOfContributorsDataSource: BaseReactiveTableViewDataSource<MemberProtocol> { private let contentRepository = ContentRepository() override init() { super.init() sections.append(ItemSection<MemberProtocol>()) fetchNotifications() } private func fetchNotifications() { disposable.add(contentRepository.retrieveHallOfContributors().observeValues {[weak self] entries in self?.sections[0].items = entries ?? [] self?.tableView?.reloadData() }) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) let member = item(at: indexPath) cell.textLabel?.text = member?.profile?.name ?? member?.username cell.textLabel?.textColor = member?.contributor?.color cell.detailTextLabel?.text = member?.contributor?.text return cell } }
2d3bb51f2568fd0a54c807acd9e6ebca
31.864865
109
0.684211
false
false
false
false
luckymarmot/ThemeKit
refs/heads/master
Sources/NSWindow+ThemeKit.swift
mit
1
// // NSWindow+ThemeKit.swift // ThemeKit // // Created by Nuno Grilo on 08/09/16. // Copyright © 2016 Paw & Nuno Grilo. All rights reserved. // import Foundation /** `NSWindow` ThemeKit extension. */ public extension NSWindow { // MARK: - // MARK: Properties /// Any window specific theme. /// /// This is, usually, `nil`, which means the current global theme will be used. /// Please note that when using window specific themes, only the associated /// `NSAppearance` will be automatically set. All theme aware assets (`ThemeColor`, /// `ThemeGradient` and `ThemeImage`) should call methods that returns a /// resolved color instead (which means they don't change with the theme change, /// you need to observe theme changes manually, and set colors afterwards): /// /// - `ThemeColor.color(for view:, selector:)` /// - `ThemeGradient.gradient(for view:, selector:)` /// - `ThemeImage.image(for view:, selector:)` /// /// Additionaly, please note that system overriden colors (`NSColor.*`) will /// always use the global theme. @objc var windowTheme: Theme? { get { return objc_getAssociatedObject(self, &themeAssociationKey) as? Theme } set(newValue) { objc_setAssociatedObject(self, &themeAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN) theme() } } /// Returns the current effective theme (read-only). @objc var windowEffectiveTheme: Theme { return windowTheme ?? ThemeManager.shared.effectiveTheme } /// Returns the current effective appearance (read-only). @objc var windowEffectiveThemeAppearance: NSAppearance? { return windowEffectiveTheme.isLightTheme ? ThemeManager.shared.lightAppearance : ThemeManager.shared.darkAppearance } // MARK: - // MARK: Theming /// Theme window if needed. @objc func theme() { if currentTheme == nil || currentTheme! != windowEffectiveTheme { // Keep record of currently applied theme currentTheme = windowEffectiveTheme // Change window tab bar appearance themeTabBar() // Change window appearance themeWindow() } } /// Theme window if compliant to ThemeManager.windowThemePolicy (and if needed). @objc func themeIfCompliantWithWindowThemePolicy() { if isCompliantWithWindowThemePolicy() { theme() } } /// Theme all windows compliant to ThemeManager.windowThemePolicy (and if needed). @objc static func themeAllWindows() { for window in windowsCompliantWithWindowThemePolicy() { window.theme() } } // MARK: - Private // MARK: - Window theme policy compliance /// Check if window is compliant with ThemeManager.windowThemePolicy. @objc internal func isCompliantWithWindowThemePolicy() -> Bool { switch ThemeManager.shared.windowThemePolicy { case .themeAllWindows: return !self.isExcludedFromTheming case .themeSomeWindows(let windowClasses): for windowClass in windowClasses where self.classForCoder === windowClass.self { return true } return false case .doNotThemeSomeWindows(let windowClasses): for windowClass in windowClasses where self.classForCoder === windowClass.self { return false } return true case .doNotThemeWindows: return false } } /// List of all existing windows compliant to ThemeManager.windowThemePolicy. @objc internal static func windowsCompliantWithWindowThemePolicy() -> [NSWindow] { var windows = [NSWindow]() switch ThemeManager.shared.windowThemePolicy { case .themeAllWindows: windows = NSApplication.shared.windows case .themeSomeWindows: windows = NSApplication.shared.windows.filter({ (window) -> Bool in return window.isCompliantWithWindowThemePolicy() }) case .doNotThemeSomeWindows: windows = NSApplication.shared.windows.filter({ (window) -> Bool in return window.isCompliantWithWindowThemePolicy() }) case .doNotThemeWindows: break } return windows } /// Returns if current window is excluded from theming @objc internal var isExcludedFromTheming: Bool { return self is NSPanel } // MARK: - Window screenshots /// Take window screenshot. @objc internal func takeScreenshot() -> NSImage? { guard let cgImage = CGWindowListCreateImage(CGRect.null, .optionIncludingWindow, CGWindowID(windowNumber), .boundsIgnoreFraming) else { return nil } let image = NSImage(cgImage: cgImage, size: frame.size) image.cacheMode = NSImage.CacheMode.never image.size = frame.size return image } /// Create a window with a screenshot of current window. @objc internal func makeScreenshotWindow() -> NSWindow { // Create "image-window" let window = NSWindow(contentRect: frame, styleMask: NSWindow.StyleMask.borderless, backing: NSWindow.BackingStoreType.buffered, defer: true) window.isOpaque = false window.backgroundColor = NSColor.clear window.ignoresMouseEvents = true window.collectionBehavior = NSWindow.CollectionBehavior.stationary window.titlebarAppearsTransparent = true // Take window screenshot if let screenshot = takeScreenshot(), let parentView = window.contentView { // Add image view let imageView = NSImageView(frame: NSRect(x: 0, y: 0, width: screenshot.size.width, height: screenshot.size.height)) imageView.image = screenshot parentView.addSubview(imageView) } return window } // MARK: - Caching /// Currently applied window theme. private var currentTheme: Theme? { get { return objc_getAssociatedObject(self, &currentThemeAssociationKey) as? Theme } set(newValue) { objc_setAssociatedObject(self, &currentThemeAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN) purgeTheme() } } private func purgeTheme() { tabBar = nil } // MARK: - Tab bar view /// Returns the tab bar view. private var tabBar: NSView? { get { // If cached, return it if let storedTabBar = objc_getAssociatedObject(self, &tabbarAssociationKey) as? NSView { return storedTabBar } var _tabBar: NSView? // Search on titlebar accessory views if supported (will fail if tab bar is hidden) let themeFrame = self.contentView?.superview if themeFrame?.responds(to: #selector(getter: titlebarAccessoryViewControllers)) ?? false { for controller: NSTitlebarAccessoryViewController in self.titlebarAccessoryViewControllers { if let possibleTabBar = controller.view.deepSubview(withClassName: "NSTabBar") { _tabBar = possibleTabBar break } } } // Search down the title bar view if _tabBar == nil { let titlebarContainerView = themeFrame?.deepSubview(withClassName: "NSTitlebarContainerView") let titlebarView = titlebarContainerView?.deepSubview(withClassName: "NSTitlebarView") _tabBar = titlebarView?.deepSubview(withClassName: "NSTabBar") } // Remember it if _tabBar != nil { objc_setAssociatedObject(self, &tabbarAssociationKey, _tabBar, .OBJC_ASSOCIATION_RETAIN) } return _tabBar } set(newValue) { objc_setAssociatedObject(self, &tabbarAssociationKey, newValue, .OBJC_ASSOCIATION_RETAIN) } } /// Check if tab bar is visbile. private var isTabBarVisible: Bool { return tabBar?.superview != nil } /// Update window appearance (if needed). private func themeWindow() { if appearance != windowEffectiveThemeAppearance { // Change window appearance appearance = windowEffectiveThemeAppearance // Invalidate shadow as sometimes it is incorrecty drawn or missing invalidateShadow() if #available(macOS 10.12, *) { // We're all good here: windows are properly refreshed! } else { // Need a trick to force update of all CALayers down the view hierarchy self.titlebarAppearsTransparent = !self.titlebarAppearsTransparent DispatchQueue.main.async { self.titlebarAppearsTransparent = !self.titlebarAppearsTransparent } } } } /// Update tab bar appearance (if needed). private func themeTabBar() { guard let _tabBar = tabBar, isTabBarVisible && _tabBar.appearance != windowEffectiveThemeAppearance else { return } // Change tabbar appearance _tabBar.appearance = windowEffectiveThemeAppearance // Refresh its subviews for tabBarSubview: NSView in _tabBar.subviews { tabBarSubview.needsDisplay = true } // Also, make sure tabbar is on top (this also properly refreshes it) if let tabbarSuperview = _tabBar.superview { tabbarSuperview.addSubview(_tabBar) } } // MARK: - Title bar view /// Returns the title bar view. private var titlebarView: NSView? { let themeFrame = self.contentView?.superview let titlebarContainerView = themeFrame?.deepSubview(withClassName: "NSTitlebarContainerView") return titlebarContainerView?.deepSubview(withClassName: "NSTitlebarView") } } private var currentThemeAssociationKey: UInt8 = 0 private var themeAssociationKey: UInt8 = 1 private var tabbarAssociationKey: UInt8 = 2
f645044021e8aaeab3a79681618d88ef
33.40604
149
0.626451
false
false
false
false
vpeschenkov/LetterAvatarKit
refs/heads/master
LetterAvatarKit/LetterAvatarMaker.swift
mit
1
// // LetterAvatarMaker.swift // LetterAvatarKit // // Copyright 2017 Victor Peschenkov // // Permission is hereby granted, free of charge, to any person obtaining a copy // o this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import UIKit import Foundation open class LetterAvatarMaker: NSObject { fileprivate var configuration = LetterAvatarBuilderConfiguration() } extension LetterAvatarMaker: LetterAvatarMakerExtendable { @discardableResult public func setSize(_ size: CGSize) -> LetterAvatarMakerExtendable { configuration.size = size return self } @discardableResult public func setUsername(_ username: String) -> LetterAvatarMakerExtendable { configuration.username = username return self } @discardableResult public func setLettersFont(_ lettersFont: UIFont?) -> LetterAvatarMakerExtendable { configuration.lettersFont = lettersFont return self } @discardableResult public func setLettersColor(_ lettersColor: UIColor) -> LetterAvatarMakerExtendable { configuration.lettersColor = lettersColor return self } @discardableResult public func useSingleLetter(_ useSingleLetter: Bool) -> LetterAvatarMakerExtendable { configuration.useSingleLetter = useSingleLetter return self } @discardableResult public func setBackgroundColors(_ backgroundColors: [UIColor]) -> LetterAvatarMakerExtendable { configuration.backgroundColors = backgroundColors return self } @discardableResult public func setLettersFontAttributes( _ lettersFontAttributes: [NSAttributedString.Key: Any]? ) -> LetterAvatarMakerExtendable { configuration.lettersFontAttributes = lettersFontAttributes return self } @discardableResult public func setBorderWidth(_ borderWidth: CGFloat) -> LetterAvatarMakerExtendable { configuration.borderWidth = borderWidth return self } @discardableResult public func setBorderColor(_ borderColor: UIColor) -> LetterAvatarMakerExtendable { configuration.borderColor = borderColor return self } @discardableResult public func setCircle(_ circle: Bool) -> LetterAvatarMakerExtendable { configuration.circle = circle return self } @discardableResult public func drawOpaqueBackground(_ isOpaque: Bool) -> LetterAvatarMakerExtendable { configuration.isOpaque = isOpaque return self } public func build(maker: (LetterAvatarBuilderConfiguration) -> Void) -> UIImage? { maker(configuration) return UIImage.makeLetterAvatar(withConfiguration: configuration) } public func build() -> UIImage? { return UIImage.makeLetterAvatar(withConfiguration: configuration) } }
1d22011e667aef24016692efd232cda9
33.790909
99
0.717272
false
true
false
false
8bytes/drift-sdk-ios
refs/heads/master
Drift/UI/Conversation View/ConversationInputAccessoryView.swift
mit
2
// // ConversationInputAccessoryView.swift // Drift-SDK // // Created by Eoin O'Connell on 24/01/2018. // Copyright © 2018 Drift. All rights reserved. // import UIKit protocol ConversationInputAccessoryViewDelegate: class { func didPressRightButton() func didPressLeftButton() func getKeyboardRect() -> CGRect func expandingKeyboard() func compressingKeyboard() func didPressView() } class ConversationInputAccessoryView: UIView { var backgroundView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = ColorPalette.shadowViewBackgroundColor return view }() var contentView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = .clear return view }() var bottomContainerView: UIView = { let bottomContainerView = UIView() bottomContainerView.translatesAutoresizingMaskIntoConstraints = false bottomContainerView.backgroundColor = .clear return bottomContainerView }() var lineView: UIView = { let view = UIView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = ColorPalette.borderColor return view }() var textView: ConversationInputTextView = { let view = ConversationInputTextView() view.translatesAutoresizingMaskIntoConstraints = false view.backgroundColor = .clear view.isScrollEnabled = false return view }() var addButton: UIButton = { let addButton = UIButton() addButton.translatesAutoresizingMaskIntoConstraints = false addButton.addTarget(self, action: #selector(didPressPlus), for: .touchUpInside) addButton.setImage(UIImage(named: "attachImage", in: Bundle.drift_getResourcesBundle(), compatibleWith: nil), for: .normal) addButton.tintColor = ColorPalette.titleTextColor return addButton }() var expandButton: UIButton = { let expandButton = UIButton() expandButton.setImage(UIImage(named: "expandButton", in: Bundle.drift_getResourcesBundle(), compatibleWith: nil), for: .normal) expandButton.translatesAutoresizingMaskIntoConstraints = false expandButton.addTarget(self, action: #selector(didPressExpand), for: .touchUpInside) expandButton.imageView?.contentMode = .center return expandButton }() var sendButton: UIButton = { let button = UIButton() button.setTitle("Send", for: .normal) button.addTarget(self, action: #selector(didPressSend), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false button.isEnabled = false button.setTitleColor(DriftDataStore.sharedInstance.generateBackgroundColor(), for: .normal) button.setTitleColor(ColorPalette.subtitleTextColor, for: .disabled) button.contentEdgeInsets = UIEdgeInsets(top: 3, left: 8, bottom: 3, right: 8) button.titleLabel?.font = UIFont(name: "AvenirNext-DemiBold", size: 14)! button.layer.cornerRadius = 3 button.layer.borderWidth = 1 button.layer.borderColor = ColorPalette.subtitleTextColor.cgColor return button }() private var textViewMaxHeightConstraint: NSLayoutConstraint! private var textViewHeightConstraint: NSLayoutConstraint! private var contentViewBottomConstraint: NSLayoutConstraint! private var backgroundBottomConstraint: NSLayoutConstraint! private var textViewTopConstraint: NSLayoutConstraint! private var textViewBottomConstraint: NSLayoutConstraint! private var windowAnchor: NSLayoutConstraint? var expanded = false weak var delegate:ConversationInputAccessoryViewDelegate? convenience init() { self.init(frame: CGRect.zero) } override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } func setup(){ autoresizingMask = .flexibleHeight textView.delegate = self let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didPressView)) tapGesture.cancelsTouchesInView = false addGestureRecognizer(tapGesture) addViews() layoutConstraints() } override var intrinsicContentSize: CGSize { //Action bar height + action bar bottom + textView intrinsic height + top var height = textViewBottomConstraint.constant height = height + bottomContainerView.frame.height height = height + textViewTopConstraint.constant height = height + textView.intrinsicContentSize.height return CGSize(width: frame.width, height: height) } override func didMoveToWindow() { super.didMoveToWindow() if #available(iOS 11.0, *) { if let window = window { windowAnchor?.isActive = false windowAnchor = contentView.bottomAnchor.constraint(lessThanOrEqualToSystemSpacingBelow: window.safeAreaLayoutGuide.bottomAnchor, multiplier: 1) windowAnchor?.constant = 0 windowAnchor?.priority = UILayoutPriority(rawValue: 750) windowAnchor?.isActive = true backgroundBottomConstraint.constant = window.safeAreaInsets.bottom } } } func setText(text: String) { textView.text = text textViewDidChange(textView) } @objc func didPressView(){ delegate?.didPressView() } func addViews(){ addSubview(backgroundView) backgroundView.addSubview(contentView) contentView.addSubview(bottomContainerView) contentView.addSubview(lineView) bottomContainerView.addSubview(addButton) bottomContainerView.addSubview(sendButton) contentView.addSubview(textView) contentView.addSubview(expandButton) } func layoutConstraints(){ //AddBackgroundView pinned to all sides backgroundBottomConstraint = backgroundView.bottomAnchor.constraint(equalTo: bottomAnchor) NSLayoutConstraint.activate([ backgroundView.leadingAnchor.constraint(equalTo: leadingAnchor), backgroundView.trailingAnchor.constraint(equalTo: trailingAnchor), backgroundView.topAnchor.constraint(equalTo: topAnchor), backgroundBottomConstraint ]) //Add Content view, top, leading, trailing, and safeArea on the bottom if #available(iOS 11.0, *) { contentViewBottomConstraint = contentView.bottomAnchor.constraint(equalTo: safeAreaLayoutGuide.bottomAnchor) } else { contentViewBottomConstraint = contentView.bottomAnchor.constraint(equalTo: backgroundView.bottomAnchor) } NSLayoutConstraint.activate([ contentView.leadingAnchor.constraint(equalTo: backgroundView.leadingAnchor), contentView.trailingAnchor.constraint(equalTo: backgroundView.trailingAnchor), contentView.topAnchor.constraint(equalTo: backgroundView.topAnchor), contentViewBottomConstraint ]) //Add Line view to top NSLayoutConstraint.activate([ lineView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), lineView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), lineView.topAnchor.constraint(equalTo: contentView.topAnchor), lineView.heightAnchor.constraint(equalToConstant: 1.0) ]) NSLayoutConstraint.activate([ bottomContainerView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: 0), bottomContainerView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 0), bottomContainerView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: 0) ]) //Add add button, leading bottom to content and width and height NSLayoutConstraint.activate([ addButton.leadingAnchor.constraint(equalTo: bottomContainerView.leadingAnchor,constant: 15), addButton.bottomAnchor.constraint(equalTo: bottomContainerView.bottomAnchor, constant: -3), addButton.topAnchor.constraint(equalTo: bottomContainerView.topAnchor, constant: 10), addButton.widthAnchor.constraint(equalToConstant: 25), addButton.heightAnchor.constraint(equalToConstant: 25) ]) //Add send button, trailing, bottom height and width, hold onto width constraint NSLayoutConstraint.activate([ sendButton.trailingAnchor.constraint(equalTo: bottomContainerView.trailingAnchor, constant: -15), sendButton.bottomAnchor.constraint(equalTo: bottomContainerView.bottomAnchor, constant: -6), sendButton.heightAnchor.constraint(equalToConstant: 30) ]) //Add textview, leading send, trailing add, top and bottom textViewMaxHeightConstraint = textView.heightAnchor.constraint(lessThanOrEqualToConstant: 150) textViewMaxHeightConstraint.priority = UILayoutPriority(999) textViewHeightConstraint = textView.heightAnchor.constraint(equalToConstant: 35) //Add textview height > 35, height < 100, height == textViewTopConstraint = textView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 0) textViewBottomConstraint = textView.bottomAnchor.constraint(equalTo: bottomContainerView.topAnchor, constant: -5) NSLayoutConstraint.activate([ textView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: 0), textView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 0), textViewBottomConstraint, textViewTopConstraint, textViewMaxHeightConstraint, textView.heightAnchor.constraint(greaterThanOrEqualToConstant: 35) ]) NSLayoutConstraint.activate([ expandButton.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -15), expandButton.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 10), expandButton.widthAnchor.constraint(equalToConstant: 30), expandButton.heightAnchor.constraint(equalToConstant: 30) ]) } func expandToggled() { if !textView.isFirstResponder { textView.becomeFirstResponder() return } if !expanded { var height = UIScreen.main.bounds.height - (delegate?.getKeyboardRect() ?? CGRect.zero).height - 80 height = max(height, 200) textViewHeightConstraint.constant = height textViewHeightConstraint.isActive = true textViewMaxHeightConstraint.isActive = false backgroundView.layer.cornerRadius = 15 lineView.alpha = 0 } else { textViewHeightConstraint.isActive = false textViewMaxHeightConstraint.isActive = true backgroundView.layer.cornerRadius = 0 lineView.alpha = 1 } expanded = !expanded if expanded{ delegate?.expandingKeyboard() } else{ delegate?.compressingKeyboard() } UIView.animate(withDuration: 0.6, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0, animations: { self.superview?.superview?.layoutIfNeeded() }, completion: nil) } func updateSendButton(enabled: Bool) { sendButton.isEnabled = enabled if enabled { sendButton.layer.borderColor = DriftDataStore.sharedInstance.generateBackgroundColor().cgColor } else { sendButton.layer.borderColor = ColorPalette.subtitleTextColor.cgColor } } @objc func didPressSend(){ if expanded { expandToggled() } delegate?.didPressRightButton() textViewDidChange(textView) //To disable the text } @objc func didPressPlus(){ delegate?.didPressLeftButton() } @objc func didPressExpand(){ expandToggled() } } extension ConversationInputAccessoryView : UITextViewDelegate { func textViewDidChange(_ textView: UITextView) { self.textView.placeholderLabel.isHidden = !textView.text.isEmpty updateSendButton(enabled: !textView.text.isEmpty) if textView.intrinsicContentSize.height >= textViewMaxHeightConstraint.constant && !textView.isScrollEnabled{ textViewHeightConstraint.constant = textView.contentSize.height textViewHeightConstraint.isActive = true textView.isScrollEnabled = true } else if textView.isScrollEnabled && textView.contentSize.height < textViewMaxHeightConstraint.constant{ textViewHeightConstraint.isActive = false textView.isScrollEnabled = false textView.invalidateIntrinsicContentSize() } else { UIView.animate(withDuration: 0.2, delay: 0, animations: { self.superview?.superview?.layoutIfNeeded() }) } } func textViewDidBeginEditing(_ textView: UITextView) { delegate?.didPressView() } }
46f55342ad26f299448f90474bca3fab
37.162983
159
0.664133
false
false
false
false
Tanglo/PepperSpray
refs/heads/master
Spray/main.swift
mit
1
// // main.swift // PepperSpray // // Created by Lee Walsh on 15/01/2016. // Copyright © 2016 Lee David Walsh. All rights reserved. // This sofware is licensed under the The MIT License (MIT) // See: https://github.com/Tanglo/PepperSpray/blob/master/LICENSE.md // import Foundation let arguments = NSProcessInfo.processInfo().arguments let workingDirectoryString = String(NSString(string: arguments[0]).stringByDeletingLastPathComponent) var nextArg = 1 if (arguments.count > nextArg) && (arguments[1] == "-h"){ PSHelp.printHelp() exit(0) } else { //Get flags var flags = PSFlags("") if arguments.count > nextArg{ let index = arguments[1].startIndex if arguments[1][index] == "-"{ flags = PSFlags(arguments[nextArg]) nextArg++ } } let createKey = !flags.contains("p") var keyPath = workingDirectoryString if (arguments.count > nextArg){ let index = arguments[1].startIndex if !(arguments[nextArg][index] == "-"){ keyPath = arguments[nextArg] nextArg++ } } var sourcePath = workingDirectoryString if (arguments.count > nextArg+1) && (arguments[nextArg] == "-s"){ sourcePath = arguments[nextArg+1] var isDirectory: ObjCBool = true NSFileManager.defaultManager().fileExistsAtPath(sourcePath, isDirectory: &isDirectory) if !isDirectory{ print("Error: <source> is not a directory") exit(-1407) //code for getting a file instead of an folder } nextArg += 2 } let overwriteFiles = flags.contains("o") var destinationPath = workingDirectoryString if (arguments.count > nextArg+1) && (arguments[nextArg] == "-d"){ destinationPath = arguments[nextArg+1] nextArg += 2 } /* print("Main: flags - \(flags)") print("Main: key? - \(createKey), keyPath - \(keyPath)") print("Main: sourcePath - \(sourcePath)") print("Main: overwrite? - \(overwriteFiles), destinationPath - \(destinationPath)") */ //Get the keyPath ready to create or overwrite a file var isDirectory: ObjCBool = true let keyFileExists = NSFileManager.defaultManager().fileExistsAtPath(keyPath, isDirectory: &isDirectory) // print("\(keyFileExists), \(isDirectory)") if keyFileExists{ if !isDirectory{ var response: String? = "a" while (response != "y") && (response != "n"){ print("Overwrite existing key file: \(keyPath)? (y/n)") response = readLine() } if response == "n"{ exit(0) } } else if keyPath.characters.last! != "/"{ //if is directory without a / keyPath += "/key.csv" } else{ //directory with a / keyPath += "key.csv" } } else if keyPath.characters.last! == "/"{ //if user specified an non-existant path ending in a / do{ //try to create the new directory try NSFileManager.defaultManager().createDirectoryAtPath(keyPath, withIntermediateDirectories: true, attributes: nil) } catch{ let nsError = (error as NSError) print("\(nsError.localizedDescription)") exit(Int32(nsError.code)) } keyPath += "key.csv" } // print("keyPath: \(keyPath)") //Get the destination path and fileStem ready let destinationExists = NSFileManager.defaultManager().fileExistsAtPath(destinationPath, isDirectory: &isDirectory) var fileStem = "file" if destinationExists{ if !isDirectory{ fileStem = String(NSString(string: destinationPath).lastPathComponent) destinationPath = String(NSString(string: destinationPath).stringByDeletingLastPathComponent) } } else if destinationPath.characters.last! == "/"{ //if user specified an non-existant path ending in a / do{ //try to create the new directory try NSFileManager.defaultManager().createDirectoryAtPath(keyPath, withIntermediateDirectories: true, attributes: nil) } catch{ let nsError = (error as NSError) print("\(nsError.localizedDescription)") exit(Int32(nsError.code)) } } else{ fileStem = String(NSString(string: destinationPath).lastPathComponent) destinationPath = String(NSString(string: destinationPath).stringByDeletingLastPathComponent) } // print("destStem: \(fileStem)") // print("destPath: \(destinationPath)") //Ready to go var filenames = [NSURL]() do{ filenames = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(NSURL(fileURLWithPath: sourcePath, isDirectory: true), includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles) } catch { let nsError = (error as NSError) print("\(nsError.localizedDescription)") exit(Int32(nsError.code)) } // print("\(filenames)") var labels = [Int]() for i in 0...filenames.count{ labels.append(i) } // print("\(labels)") for url in filenames{ let fileSourcePath = url.path! let fileDestinationPathStem = destinationPath + "/" + fileStem let fileExtension = NSString(string: url.path!).pathExtension let numberIndex = Int(arc4random_uniform(UInt32(filenames.count))) let number = "\(labels[numberIndex])" labels.removeAtIndex(numberIndex) let numberString = number.stringByPaddingToLength(5, withString: "0", startingAtIndex: 0) number.str print("source: \(fileSourcePath)") print("destination: \(fileDestinationPathStem)") print("fileExtension: \(fileExtension)") print("numberString: \(numberString)") } }
639057bb7362627bcd8f752f80e48b0a
39.127517
224
0.610804
false
false
false
false
hchhatbar/SAHC_iOS_App
refs/heads/master
SAHC/SAHC/HRAViewController.swift
mit
1
// // HRAViewController.swift // SAHC // // Created by Hemen Chhatbar on 10/25/15. // Copyright (c) 2015 AppForCause. All rights reserved. // import UIKit import CoreData class HRAViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet var checkListTblView: UITableView! var hud: MBProgressHUD = MBProgressHUD() var checkList: [SurveyCategory] = [SurveyCategory]() // var scroll = UIScrollView() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. print(Service.sharedInstance.sessionKey) self.hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true) self.hud.mode = MBProgressHUDMode.AnnularDeterminate self.hud.label.text = NSLocalizedString("Loading Questions...", comment: "Loading questions for spinner") dispatch_async(dispatch_get_global_queue( DISPATCH_QUEUE_PRIORITY_LOW, 0), { Service.sharedInstance.refreshCategories { (inner: () throws -> Bool) -> Void in do { let success = try inner() // get result if success { self.checkList = Service.sharedInstance.survey.categories dispatch_async(dispatch_get_main_queue(), { self.checkListTblView.reloadData() self.hud.hideAnimated(true) }) } } catch let error { print(error) } } Service.sharedInstance.refreshQuestions { (inner: () throws -> Bool) -> Void in // dismiss spinner // dispatch_async(dispatch_get_main_queue(), { // hud.hideAnimated(true) // }) do { let success = try inner() // get result if success { // populate answers from db for question in Service.sharedInstance.survey.questions { // need to migrate this to DataController later let moc = DataController.sharedInstance.managedObjectContext let fetchRequest = NSFetchRequest(entityName: "SurveyAnswer") fetchRequest.predicate = NSPredicate(format: "questionId == %d", question.id) do { let surveyAnswers = try moc.executeFetchRequest(fetchRequest) as! [SurveyAnswer] // really inefficient, trying to resave the values back to db if surveyAnswers.count > 0 { // there should only be one result anyways for surveyAnswer in surveyAnswers { if question.type == QuestionViewController.QuestionType.InputAnswer.rawValue { question.answerTxt = surveyAnswer.answerTxt } else { for answerValue in surveyAnswer.answerValues as! [Int] { if let answerOptions = question.answerOptions { for answerOption in answerOptions { if answerValue == answerOption.value { answerOption.selected = true } } } } } } } } catch { fatalError("Failed to fetch: \(error)") } } } // end if success } catch let error { print(error) } } }) // Service.getQuestionsWithSuccess { (questions) -> Void in // let json = JSON(data: questions) // print(json) // //let dataAccess = DataAccess() // //DataAccess.sharedInstance.saveQuestions(json) // _ = DataAccess.sharedInstance.getQuestions() // } //Service.getQuestions({ (questions) -> Void in // println(questions) //} ) // Get the #1 app name from iTunes and SwiftyJSON /* Service.getQuestionsWithSuccess { (questions) -> Void in let json = JSON(data: questions) var dataAccess = DataAccess() dataAccess.saveQuestions(json) var results = dataAccess.getQuestions() // More soon... //1 /* if let appArray = json["feed"]["entry"].array { //2 var apps = [AppModel]() //3 for appDict in appArray { var appName: String? = appDict["im:name"]["label"].string var appURL: String? = appDict["im:image"][0]["label"].string var app = AppModel(name: appName, appStoreURL: appURL) apps.append(app) } //4 println(apps) var dataAccess = DataAccess() dataAccess.saveQuestions() var results = dataAccess.getQuestions()*/ } */ } // func getQuestionsFromJSON(){ // // // } // // override func viewWillAppear(animated: Bool) { // scroll.backgroundColor = UIColor.redColor(); // scroll.scrollEnabled = true // scroll.pagingEnabled = true; // self.view.addSubview(scroll) // } // // @IBAction func introductionClicked(sender: AnyObject) { // let questionTableViewController = QuestionTableViewController() // self.view.addSubview(questionTableViewController.view) // } // override func didReceiveMemoryWarning() { // super.didReceiveMemoryWarning() // // Dispose of any resources that can be recreated. // } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { let index = sender as! Int if segue.destinationViewController is QuestionViewController { let viewController = segue.destinationViewController as! QuestionViewController viewController.navigationItem.title = self.checkList[index].section viewController.questions = Service.sharedInstance.survey.questions.filter({ $0.category == String(index+1) }) } } // MARK: UITableViewDataSource methods func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.checkList.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("HRATableViewCell") as! HRATableViewCell cell.itemImageView.image = UIImage(named: self.checkList[indexPath.row].section) cell.itemNameLbl.text = self.checkList[indexPath.row].section //cell.progressView.progress = self.initialHRACheckList[indexPath.row].progress return cell } // MARK: End UITableViewDataSource methods func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { // check if there are actual questions behind the category if Service.sharedInstance.survey.questions.filter({ $0.category == String(indexPath.row+1) }).count > 0 { self.performSegueWithIdentifier("DashboardToQuestionaireSegue", sender: indexPath.row) } } // MARK: UITableViewDelegate methods // MARK: End UITableViewDelegate methods // MARK: Target-Actions @IBAction func signoutBtnPressed(sender: AnyObject) { self.dismissViewControllerAnimated(true, completion: nil) } // MARK: End Target-Actions }
14bc576ea0836a27aa124bc85839fd8c
39.853333
122
0.48205
false
false
false
false
heilb1314/500px_Challenge
refs/heads/master
PhotoWall_500px_challenge/PhotoWall_500px_challenge/Photo.swift
mit
1
// // Photo.swift // demo_500px // // Created by Jianxiong Wang on 1/29/17. // Copyright © 2017 JianxiongWang. All rights reserved. // import UIKit /** * Photo Object with photo attributes and images information, Images cannot be nil */ public class Photo { public var name:String? public var description: String? public var images:[ImageObject] public var attributes:[String:Any] init(photoItem: [String:Any]) throws { images = [ImageObject]() attributes = [String:Any]() // iterate through key-val and parse them for(key,val) in photoItem { switch key { case PhotoFields.name: self.name = val as? String case PhotoFields.description: self.description = val as? String case PhotoFields.images: guard let imagesDic = val as? [[String:Any]] else { throw PhotoError.imageNotFound } try self.parseImages(imagesDic: imagesDic) default: attributes.updateValue(val, forKey: key) } } if self.images.isEmpty { throw PhotoError.imageNotFound } } /// Get Photo Size, if either width or height not found return 180X180 public func getPhotoSize() -> CGSize { if let width = attributes[PhotoFields.width] as? Int { if let height = attributes[PhotoFields.height] as? Int { return CGSize(width: width, height: height) } } return CGSize(width: 180, height: 180) } /** * Parse images with images array, images cannot be empty. * * - Parameter imagesDic: images array gets from query json object photos */ private func parseImages(imagesDic:[[String:Any]]) throws { for image in imagesDic { do { images.append(try ImageObject(imageDictionary: image)) } catch { print("Fail to create Image Object: ", error.localizedDescription) continue } } if images.isEmpty { throw PhotoError.imageNotFound } } // MARK: - Class functions /** * Parse photos from json query object "photos". * * - Parameter dic: photos dictionary gets from query JSON object * - Returns: Photo array, can be nil */ internal class func parsePhotos(withDictionary dic: [String:Any]) throws -> [Photo]? { if let photos = dic[QueryFields.photos] as? [Any] { var results = [Photo]() for item in photos { if let photoDic = item as? [String: Any] { do { results.append(try Photo(photoItem: photoDic)) } catch { print("Fail parse photo: ", error) continue; } } else { print("Not a dictionary.") } } return results } return nil } } /// Image Object using dictionary of Photos 'images' property public class ImageObject { var url:String var format: String var size: Int init(imageDictionary dic: [String:Any]) throws { guard let url = dic[ImagesFields.url] as? String else { throw ImageObjectError.noUrlFound } guard let format = dic[ImagesFields.format] as? String else { throw ImageObjectError.noFormatFound } guard let size = dic[ImagesFields.size] as? Int else { throw ImageObjectError.noSizeFound } self.url = url self.format = format self.size = size } }
6e84f969380d579a4edbf427ab04aab9
29.557377
108
0.557403
false
false
false
false
RevenueCat/purchases-ios
refs/heads/main
Tests/UnitTests/Networking/Backend/BackendPostOfferForSigningTests.swift
mit
1
// // 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 // // BackendPostOfferForSigningTests.swift // // Created by Nacho Soto on 3/7/22. import Foundation import Nimble import XCTest @testable import RevenueCat class BackendPostOfferForSigningTests: BaseBackendTests { override func createClient() -> MockHTTPClient { super.createClient(#file) } func testOfferForSigningCorrectly() throws { let validSigningResponse: [String: Any] = [ "offers": [ [ "offer_id": "PROMO_ID", "product_id": "com.myapp.product_a", "key_id": "STEAKANDEGGS", "signature_data": [ "signature": "Base64 encoded signature", "nonce": "A UUID", "timestamp": Int64(123413232131) ], "signature_error": nil ] ] ] let path: HTTPRequest.Path = .postOfferForSigning let response = MockHTTPClient.Response(statusCode: .success, response: validSigningResponse) self.httpClient.mock(requestPath: path, response: response) let productIdentifier = "a_great_product" let group = "sub_group" var completionCalled = false let offerIdentifier = "offerid" let discountData = "an awesome discount".asData self.offerings.post(offerIdForSigning: offerIdentifier, productIdentifier: productIdentifier, subscriptionGroup: group, receiptData: discountData, appUserID: Self.userID) { _ in completionCalled = true } expect(self.httpClient.calls).toEventually(haveCount(1)) expect(completionCalled).toEventually(beTrue()) } func testOfferForSigningNetworkError() { let mockedError = NetworkError.unexpectedResponse(nil) self.httpClient.mock( requestPath: .postOfferForSigning, response: .init(error: mockedError) ) let productIdentifier = "a_great_product" let group = "sub_group" let offerIdentifier = "offerid" let discountData = "an awesome discount".data(using: String.Encoding.utf8)! var result: Result<PostOfferForSigningOperation.SigningData, BackendError>? self.offerings.post(offerIdForSigning: offerIdentifier, productIdentifier: productIdentifier, subscriptionGroup: group, receiptData: discountData, appUserID: Self.userID) { result = $0 } expect(result).toEventuallyNot(beNil()) expect(result).to(beFailure()) expect(result?.error) == .networkError(mockedError) } func testOfferForSigningEmptyOffersResponse() { let validSigningResponse: [String: Any] = [ "offers": [] ] self.httpClient.mock( requestPath: .postOfferForSigning, response: .init(statusCode: .success, response: validSigningResponse) ) let productIdentifier = "a_great_product" let group = "sub_group" let offerIdentifier = "offerid" let discountData = "an awesome discount".data(using: String.Encoding.utf8)! var receivedError: BackendError? self.offerings.post(offerIdForSigning: offerIdentifier, productIdentifier: productIdentifier, subscriptionGroup: group, receiptData: discountData, appUserID: Self.userID) { result in receivedError = result.error } expect(receivedError).toEventuallyNot(beNil()) expect(receivedError) == .unexpectedBackendResponse(.postOfferIdMissingOffersInResponse) } func testOfferForSigningSignatureErrorResponse() { let errorResponse = ErrorResponse(code: .invalidAppleSubscriptionKey, originalCode: 7234, message: "Ineligible for some reason") let validSigningResponse: [String: Any] = [ "offers": [ [ "offer_id": "PROMO_ID", "product_id": "com.myapp.product_a", "key_id": "STEAKANDEGGS", "signature_data": nil, "signature_error": [ "message": errorResponse.message!, "code": errorResponse.code.rawValue ] ] ] ] self.httpClient.mock( requestPath: .postOfferForSigning, response: .init(statusCode: .success, response: validSigningResponse) ) let productIdentifier = "a_great_product" let group = "sub_group" let offerIdentifier = "offerid" let discountData = "an awesome discount".data(using: String.Encoding.utf8)! var receivedError: BackendError? self.offerings.post(offerIdForSigning: offerIdentifier, productIdentifier: productIdentifier, subscriptionGroup: group, receiptData: discountData, appUserID: Self.userID) { result in receivedError = result.error } expect(receivedError).toEventuallyNot(beNil()) expect(receivedError) == .networkError(.errorResponse(errorResponse, .success)) } func testOfferForSigningNoDataAndNoSignatureErrorResponse() { let validSigningResponse: [String: Any] = [ "offers": [ [ "offer_id": "PROMO_ID", "product_id": "com.myapp.product_a", "key_id": "STEAKANDEGGS", "signature_data": nil, "signature_error": nil ] ] ] self.httpClient.mock( requestPath: .postOfferForSigning, response: .init(statusCode: .success, response: validSigningResponse) ) let productIdentifier = "a_great_product" let group = "sub_group" let offerIdentifier = "offerid" let discountData = "an awesome discount".data(using: String.Encoding.utf8)! var receivedError: BackendError? self.offerings.post(offerIdForSigning: offerIdentifier, productIdentifier: productIdentifier, subscriptionGroup: group, receiptData: discountData, appUserID: Self.userID) { result in receivedError = result.error } expect(receivedError).toEventuallyNot(beNil()) guard case .unexpectedBackendResponse(.postOfferIdSignature, _, _) = receivedError else { fail("Invalid error: \(String(describing: receivedError))") return } } }
ee9365cf288975125d7ea138a8f294c5
34.325359
100
0.558987
false
false
false
false
segmentio/analytics-swift
refs/heads/main
Sources/Segment/Settings.swift
mit
1
// // Settings.swift // Segment // // Created by Cody Garvin on 12/15/20. // import Foundation public struct Settings: Codable { public var integrations: JSON? = nil public var plan: JSON? = nil public var edgeFunction: JSON? = nil public var middlewareSettings: JSON? = nil public init(writeKey: String, apiHost: String) { integrations = try! JSON([ SegmentDestination.Constants.integrationName.rawValue: [ SegmentDestination.Constants.apiKey.rawValue: writeKey, SegmentDestination.Constants.apiHost.rawValue: apiHost ] ]) } public init(writeKey: String) { integrations = try! JSON([ SegmentDestination.Constants.integrationName.rawValue: [ SegmentDestination.Constants.apiKey.rawValue: writeKey, SegmentDestination.Constants.apiHost.rawValue: HTTPClient.getDefaultAPIHost() ] ]) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.integrations = try? values.decode(JSON.self, forKey: CodingKeys.integrations) self.plan = try? values.decode(JSON.self, forKey: CodingKeys.plan) self.edgeFunction = try? values.decode(JSON.self, forKey: CodingKeys.edgeFunction) self.middlewareSettings = try? values.decode(JSON.self, forKey: CodingKeys.middlewareSettings) } enum CodingKeys: String, CodingKey { case integrations case plan case edgeFunction case middlewareSettings } /** * Easily retrieve settings for a specific integration name. * * - Parameter for: The string name of the integration * - Returns: The dictionary representing the settings for this integration as supplied by Segment.com */ public func integrationSettings(forKey key: String) -> [String: Any]? { guard let settings = integrations?.dictionaryValue else { return nil } let result = settings[key] as? [String: Any] return result } public func integrationSettings<T: Codable>(forKey key: String) -> T? { var result: T? = nil guard let settings = integrations?.dictionaryValue else { return nil } if let dict = settings[key], let jsonData = try? JSONSerialization.data(withJSONObject: dict) { result = try? JSONDecoder().decode(T.self, from: jsonData) } return result } public func integrationSettings<T: Codable>(forPlugin plugin: DestinationPlugin) -> T? { return integrationSettings(forKey: plugin.key) } public func hasIntegrationSettings(forPlugin plugin: DestinationPlugin) -> Bool { return hasIntegrationSettings(key: plugin.key) } public func hasIntegrationSettings(key: String) -> Bool { guard let settings = integrations?.dictionaryValue else { return false } return (settings[key] != nil) } } extension Settings: Equatable { public static func == (lhs: Settings, rhs: Settings) -> Bool { let l = lhs.prettyPrint() let r = rhs.prettyPrint() return l == r } } extension Analytics { internal func update(settings: Settings, type: UpdateType) { apply { (plugin) in // tell all top level plugins to update. update(plugin: plugin, settings: settings, type: type) } } internal func update(plugin: Plugin, settings: Settings, type: UpdateType) { plugin.update(settings: settings, type: type) // if it's a destination, tell it's plugins to update as well. if let dest = plugin as? DestinationPlugin { dest.apply { (subPlugin) in subPlugin.update(settings: settings, type: type) } } } internal func checkSettings() { #if DEBUG if isUnitTesting { // we don't really wanna wait for this network call during tests... // but we should make it work similarly. store.dispatch(action: System.ToggleRunningAction(running: false)) DispatchQueue.main.async { if let state: System = self.store.currentState(), let settings = state.settings { self.store.dispatch(action: System.UpdateSettingsAction(settings: settings)) } self.store.dispatch(action: System.ToggleRunningAction(running: true)) } return } #endif let writeKey = self.configuration.values.writeKey let httpClient = HTTPClient(analytics: self) let systemState: System? = store.currentState() let hasSettings = (systemState?.settings?.integrations != nil && systemState?.settings?.plan != nil) let updateType = (hasSettings ? UpdateType.refresh : UpdateType.initial) // stop things; queue in case our settings have changed. store.dispatch(action: System.ToggleRunningAction(running: false)) httpClient.settingsFor(writeKey: writeKey) { (success, settings) in if success { if let s = settings { // put the new settings in the state store. // this will cause them to be cached. self.store.dispatch(action: System.UpdateSettingsAction(settings: s)) // let plugins know we just received some settings.. self.update(settings: s, type: updateType) } } // we're good to go back to a running state. self.store.dispatch(action: System.ToggleRunningAction(running: true)) } } }
e25e8856b501fbd486dc178111f60dd4
37.858108
108
0.620762
false
false
false
false
kaideyi/KDYSample
refs/heads/master
KYChat/Pods/BSImagePicker/Pod/Classes/Controller/PhotosViewController.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2015 Joakim Gyllström // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit import Photos import BSGridCollectionViewLayout fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l < r case (nil, _?): return true default: return false } } fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool { switch (lhs, rhs) { case let (l?, r?): return l > r default: return rhs < lhs } } final class PhotosViewController : UICollectionViewController { var selectionClosure: ((_ asset: PHAsset) -> Void)? var deselectionClosure: ((_ asset: PHAsset) -> Void)? var cancelClosure: ((_ assets: [PHAsset]) -> Void)? var finishClosure: ((_ assets: [PHAsset]) -> Void)? var doneBarButton: UIBarButtonItem? var cancelBarButton: UIBarButtonItem? var albumTitleView: AlbumTitleView? let expandAnimator = ZoomAnimator() let shrinkAnimator = ZoomAnimator() fileprivate var photosDataSource: PhotoCollectionViewDataSource? fileprivate var albumsDataSource: AlbumTableViewDataSource fileprivate let cameraDataSource: CameraCollectionViewDataSource fileprivate var composedDataSource: ComposedCollectionViewDataSource? fileprivate var defaultSelections: PHFetchResult<PHAsset>? let settings: BSImagePickerSettings fileprivate var doneBarButtonTitle: String? lazy var albumsViewController: AlbumsViewController = { let storyboard = UIStoryboard(name: "Albums", bundle: BSImagePickerViewController.bundle) let vc = storyboard.instantiateInitialViewController() as! AlbumsViewController vc.tableView.dataSource = self.albumsDataSource vc.tableView.delegate = self return vc }() fileprivate lazy var previewViewContoller: PreviewViewController? = { return PreviewViewController(nibName: nil, bundle: nil) }() required init(fetchResults: [PHFetchResult<PHAssetCollection>], defaultSelections: PHFetchResult<PHAsset>? = nil, settings aSettings: BSImagePickerSettings) { albumsDataSource = AlbumTableViewDataSource(fetchResults: fetchResults) cameraDataSource = CameraCollectionViewDataSource(settings: aSettings, cameraAvailable: UIImagePickerController.isSourceTypeAvailable(.camera)) self.defaultSelections = defaultSelections settings = aSettings super.init(collectionViewLayout: GridCollectionViewLayout()) PHPhotoLibrary.shared().register(self) } required init?(coder aDecoder: NSCoder) { fatalError("b0rk: initWithCoder not implemented") } deinit { PHPhotoLibrary.shared().unregisterChangeObserver(self) } override func loadView() { super.loadView() // Setup collection view collectionView?.backgroundColor = UIColor.white collectionView?.allowsMultipleSelection = true // Set an empty title to get < back button title = " " // Set button actions and add them to navigation item doneBarButton?.target = self doneBarButton?.action = #selector(PhotosViewController.doneButtonPressed(_:)) cancelBarButton?.target = self cancelBarButton?.action = #selector(PhotosViewController.cancelButtonPressed(_:)) albumTitleView?.albumButton?.addTarget(self, action: #selector(PhotosViewController.albumButtonPressed(_:)), for: .touchUpInside) navigationItem.leftBarButtonItem = cancelBarButton navigationItem.rightBarButtonItem = doneBarButton navigationItem.titleView = albumTitleView if let album = albumsDataSource.fetchResults.first?.firstObject { initializePhotosDataSource(album, selections: defaultSelections) updateAlbumTitle(album) collectionView?.reloadData() } // Add long press recognizer let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(PhotosViewController.collectionViewLongPressed(_:))) longPressRecognizer.minimumPressDuration = 0.5 collectionView?.addGestureRecognizer(longPressRecognizer) // Set navigation controller delegate navigationController?.delegate = self // Register cells photosDataSource?.registerCellIdentifiersForCollectionView(collectionView) cameraDataSource.registerCellIdentifiersForCollectionView(collectionView) } // MARK: Appear/Disappear override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateDoneButton() } // MARK: Button actions func cancelButtonPressed(_ sender: UIBarButtonItem) { guard let closure = cancelClosure, let photosDataSource = photosDataSource else { dismiss(animated: true, completion: nil) return } DispatchQueue.global().async { closure(photosDataSource.selections) } dismiss(animated: true, completion: nil) } func doneButtonPressed(_ sender: UIBarButtonItem) { guard let closure = finishClosure, let photosDataSource = photosDataSource else { dismiss(animated: true, completion: nil) return } DispatchQueue.global().async { closure(photosDataSource.selections) } dismiss(animated: true, completion: nil) } func albumButtonPressed(_ sender: UIButton) { guard let popVC = albumsViewController.popoverPresentationController else { return } popVC.permittedArrowDirections = .up popVC.sourceView = sender let senderRect = sender.convert(sender.frame, from: sender.superview) let sourceRect = CGRect(x: senderRect.origin.x, y: senderRect.origin.y + (sender.frame.size.height / 2), width: senderRect.size.width, height: senderRect.size.height) popVC.sourceRect = sourceRect popVC.delegate = self albumsViewController.tableView.reloadData() present(albumsViewController, animated: true, completion: nil) } func collectionViewLongPressed(_ sender: UIGestureRecognizer) { if sender.state == .began { // Disable recognizer while we are figuring out location and pushing preview sender.isEnabled = false collectionView?.isUserInteractionEnabled = false // Calculate which index path long press came from let location = sender.location(in: collectionView) let indexPath = collectionView?.indexPathForItem(at: location) if let vc = previewViewContoller, let indexPath = indexPath, let cell = collectionView?.cellForItem(at: indexPath) as? PhotoCell, let asset = cell.asset { // Setup fetch options to be synchronous let options = PHImageRequestOptions() options.isSynchronous = true // Load image for preview if let imageView = vc.imageView { PHCachingImageManager.default().requestImage(for: asset, targetSize:imageView.frame.size, contentMode: .aspectFit, options: options) { (result, _) in imageView.image = result } } // Setup animation expandAnimator.sourceImageView = cell.imageView expandAnimator.destinationImageView = vc.imageView shrinkAnimator.sourceImageView = vc.imageView shrinkAnimator.destinationImageView = cell.imageView navigationController?.pushViewController(vc, animated: true) } // Re-enable recognizer, after animation is done DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(expandAnimator.transitionDuration(using: nil) * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: { () -> Void in sender.isEnabled = true self.collectionView?.isUserInteractionEnabled = true }) } } // MARK: Private helper methods func updateDoneButton() { // Find right button if let subViews = navigationController?.navigationBar.subviews, let photosDataSource = photosDataSource { for view in subViews { if let btn = view as? UIButton , checkIfRightButtonItem(btn) { // Store original title if we havn't got it if doneBarButtonTitle == nil { doneBarButtonTitle = btn.title(for: UIControlState()) } // Update title if let doneBarButtonTitle = doneBarButtonTitle { // Special case if we have selected 1 image and that is // the max number of allowed selections if (photosDataSource.selections.count == 1 && self.settings.maxNumberOfSelections == 1) { btn.bs_setTitleWithoutAnimation("\(doneBarButtonTitle)", forState: UIControlState()) } else if photosDataSource.selections.count > 0 { btn.bs_setTitleWithoutAnimation("\(doneBarButtonTitle) (\(photosDataSource.selections.count))", forState: UIControlState()) } else { btn.bs_setTitleWithoutAnimation(doneBarButtonTitle, forState: UIControlState()) } // Enabled? doneBarButton?.isEnabled = photosDataSource.selections.count > 0 } // Stop loop break } } } } // Check if a give UIButton is the right UIBarButtonItem in the navigation bar // Somewhere along the road, our UIBarButtonItem gets transformed to an UINavigationButton func checkIfRightButtonItem(_ btn: UIButton) -> Bool { guard let rightButton = navigationItem.rightBarButtonItem else { return false } // Store previous values let wasRightEnabled = rightButton.isEnabled let wasButtonEnabled = btn.isEnabled // Set a known state for both buttons rightButton.isEnabled = false btn.isEnabled = false // Change one and see if other also changes rightButton.isEnabled = true let isRightButton = btn.isEnabled // Reset rightButton.isEnabled = wasRightEnabled btn.isEnabled = wasButtonEnabled return isRightButton } func updateAlbumTitle(_ album: PHAssetCollection) { if let title = album.localizedTitle { // Update album title albumTitleView?.albumTitle = title } } func initializePhotosDataSource(_ album: PHAssetCollection, selections: PHFetchResult<PHAsset>? = nil) { // Set up a photo data source with album let fetchOptions = PHFetchOptions() fetchOptions.sortDescriptors = [ NSSortDescriptor(key: "creationDate", ascending: false) ] fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue) initializePhotosDataSourceWithFetchResult(PHAsset.fetchAssets(in: album, options: fetchOptions), selections: selections) } func initializePhotosDataSourceWithFetchResult(_ fetchResult: PHFetchResult<PHAsset>, selections: PHFetchResult<PHAsset>? = nil) { let newDataSource = PhotoCollectionViewDataSource(fetchResult: fetchResult, selections: selections, settings: settings) // Transfer image size // TODO: Move image size to settings if let photosDataSource = photosDataSource { newDataSource.imageSize = photosDataSource.imageSize newDataSource.selections = photosDataSource.selections } photosDataSource = newDataSource // Hook up data source composedDataSource = ComposedCollectionViewDataSource(dataSources: [cameraDataSource, newDataSource]) collectionView?.dataSource = composedDataSource collectionView?.delegate = self } } // MARK: UICollectionViewDelegate extension PhotosViewController { override func collectionView(_ collectionView: UICollectionView, shouldSelectItemAt indexPath: IndexPath) -> Bool { // NOTE: ALWAYS return false. We don't want the collectionView to be the source of thruth regarding selections // We can manage it ourself. // Camera shouldn't be selected, but pop the UIImagePickerController! if let composedDataSource = composedDataSource , composedDataSource.dataSources[indexPath.section].isEqual(cameraDataSource) { let cameraController = UIImagePickerController() cameraController.allowsEditing = false cameraController.sourceType = .camera cameraController.delegate = self self.present(cameraController, animated: true, completion: nil) return false } // Make sure we have a data source and that we can make selections guard let photosDataSource = photosDataSource, collectionView.isUserInteractionEnabled else { return false } // We need a cell guard let cell = collectionView.cellForItem(at: indexPath) as? PhotoCell else { return false } let asset = photosDataSource.fetchResult.object(at: indexPath.row) // Select or deselect? if let index = photosDataSource.selections.index(of: asset) { // Deselect // Deselect asset photosDataSource.selections.remove(at: index) // Update done button updateDoneButton() // Get indexPaths of selected items let selectedIndexPaths = photosDataSource.selections.flatMap({ (asset) -> IndexPath? in let index = photosDataSource.fetchResult.index(of: asset) guard index != NSNotFound else { return nil } return IndexPath(item: index, section: 1) }) // Reload selected cells to update their selection number UIView.setAnimationsEnabled(false) collectionView.reloadItems(at: selectedIndexPaths) UIView.setAnimationsEnabled(true) cell.photoSelected = false // Call deselection closure if let closure = deselectionClosure { DispatchQueue.global().async { closure(asset) } } } else if photosDataSource.selections.count < settings.maxNumberOfSelections { // Select // Select asset if not already selected photosDataSource.selections.append(asset) // Set selection number if let selectionCharacter = settings.selectionCharacter { cell.selectionString = String(selectionCharacter) } else { cell.selectionString = String(photosDataSource.selections.count) } cell.photoSelected = true // Update done button updateDoneButton() // Call selection closure if let closure = selectionClosure { DispatchQueue.global().async { closure(asset) } } } return false } override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let cell = cell as? CameraCell else { return } cell.startLiveBackground() // Start live background } } // MARK: UIPopoverPresentationControllerDelegate extension PhotosViewController: UIPopoverPresentationControllerDelegate { func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return .none } func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool { return true } } // MARK: UINavigationControllerDelegate extension PhotosViewController: UINavigationControllerDelegate { func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationControllerOperation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? { if operation == .push { return expandAnimator } else { return shrinkAnimator } } } // MARK: UITableViewDelegate extension PhotosViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Update photos data source let album = albumsDataSource.fetchResults[indexPath.section][indexPath.row] initializePhotosDataSource(album) updateAlbumTitle(album) collectionView?.reloadData() // Dismiss album selection albumsViewController.dismiss(animated: true, completion: nil) } } // MARK: Traits extension PhotosViewController { override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if let collectionViewFlowLayout = collectionViewLayout as? GridCollectionViewLayout { let itemSpacing: CGFloat = 2.0 let cellsPerRow = settings.cellsPerRow(traitCollection.verticalSizeClass, traitCollection.horizontalSizeClass) collectionViewFlowLayout.itemSpacing = itemSpacing collectionViewFlowLayout.itemsPerRow = cellsPerRow photosDataSource?.imageSize = collectionViewFlowLayout.itemSize updateDoneButton() } } } // MARK: UIImagePickerControllerDelegate extension PhotosViewController: UIImagePickerControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { guard let image = info[UIImagePickerControllerOriginalImage] as? UIImage else { picker.dismiss(animated: true, completion: nil) return } var placeholder: PHObjectPlaceholder? PHPhotoLibrary.shared().performChanges({ let request = PHAssetChangeRequest.creationRequestForAsset(from: image) placeholder = request.placeholderForCreatedAsset }, completionHandler: { success, error in guard let placeholder = placeholder, let asset = PHAsset.fetchAssets(withLocalIdentifiers: [placeholder.localIdentifier], options: nil).firstObject, success == true else { picker.dismiss(animated: true, completion: nil) return } DispatchQueue.main.async { // TODO: move to a function. this is duplicated in didSelect self.photosDataSource?.selections.append(asset) self.updateDoneButton() // Call selection closure if let closure = self.selectionClosure { DispatchQueue.global().async { closure(asset) } } picker.dismiss(animated: true, completion: nil) } }) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { picker.dismiss(animated: true, completion: nil) } } // MARK: PHPhotoLibraryChangeObserver extension PhotosViewController: PHPhotoLibraryChangeObserver { func photoLibraryDidChange(_ changeInstance: PHChange) { guard let photosDataSource = photosDataSource, let collectionView = collectionView else { return } DispatchQueue.main.async(execute: { () -> Void in if let photosChanges = changeInstance.changeDetails(for: photosDataSource.fetchResult as! PHFetchResult<PHObject>) { // Update collection view // Alright...we get spammed with change notifications, even when there are none. So guard against it if photosChanges.hasIncrementalChanges && (photosChanges.removedIndexes?.count > 0 || photosChanges.insertedIndexes?.count > 0 || photosChanges.changedIndexes?.count > 0) { // Update fetch result photosDataSource.fetchResult = photosChanges.fetchResultAfterChanges as! PHFetchResult<PHAsset> if let removed = photosChanges.removedIndexes { collectionView.deleteItems(at: removed.bs_indexPathsForSection(1)) } if let inserted = photosChanges.insertedIndexes { collectionView.insertItems(at: inserted.bs_indexPathsForSection(1)) } // Changes is causing issues right now...fix me later // Example of issue: // 1. Take a new photo // 2. We will get a change telling to insert that asset // 3. While it's being inserted we get a bunch of change request for that same asset // 4. It flickers when reloading it while being inserted // TODO: FIX // if let changed = photosChanges.changedIndexes { // print("changed") // collectionView.reloadItemsAtIndexPaths(changed.bs_indexPathsForSection(1)) // } // Reload view collectionView.reloadData() } else if photosChanges.hasIncrementalChanges == false { // Update fetch result photosDataSource.fetchResult = photosChanges.fetchResultAfterChanges as! PHFetchResult<PHAsset> collectionView.reloadData() // Reload view collectionView.reloadData() } } }) // TODO: Changes in albums } }
bd5bfa353e4b4d4b8d7333ed347c0a4d
41.821747
246
0.630437
false
false
false
false
justindhill/Facets
refs/heads/master
Facets/View Controllers/Form Builder/OZLTextViewFormField.swift
mit
1
// // OZLTextAreaFormField.swift // Facets // // Created by Justin Hill on 3/15/16. // Copyright © 2016 Justin Hill. All rights reserved. // import JVFloatLabeledTextField class OZLTextViewFormField: OZLFormField { var currentValue: String? init(keyPath: String, placeholder: String, currentValue: String? = nil) { self.currentValue = currentValue super.init(keyPath: keyPath, placeholder: placeholder) self.fieldHeight = 150.0 self.cellClass = OZLTextViewFormFieldCell.self } } class OZLTextViewFormFieldCell: OZLFormFieldCell, UITextViewDelegate { var textView = JVFloatLabeledTextView() fileprivate var valueBeforeEditing: String? required init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.textView.delegate = self } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.textView.delegate = self } override func applyFormField(_ field: OZLFormField) { super.applyFormField(field) guard let field = field as? OZLTextViewFormField else { assertionFailure("Somehow got passed the wrong type of field") return } self.textView.placeholder = field.placeholder self.textView.text = field.currentValue } override func layoutSubviews() { super.layoutSubviews() if self.textView.superview == nil { self.contentView.addSubview(self.textView) } self.textView.frame = self.contentView.bounds self.textView.frame.origin.x += self.layoutMargins.left self.textView.frame.size.width -= (self.layoutMargins.left + self.layoutMargins.right) self.textView.floatingLabelYPadding = 8 self.textView.layoutSubviews() } func textViewShouldBeginEditing(_ textView: UITextView) -> Bool { if self.delegate?.formFieldCellWillBeginEditing(self, firstResponder: self) ?? true { self.valueBeforeEditing = textView.text return true } return false } func textViewShouldEndEditing(_ textView: UITextView) -> Bool { if textView.text != self.valueBeforeEditing { let oldValue = self.valueBeforeEditing != "" ? self.valueBeforeEditing : nil let newValue = textView.text != "" ? textView.text : nil self.delegate?.formFieldCell(self, valueChangedFrom: oldValue as AnyObject?, toValue: newValue as AnyObject?, atKeyPath: self.keyPath, userInfo: self.userInfo) } return true } }
5ae663082330be7636ebda8d6cbc9385
30.376471
171
0.664792
false
false
false
false
frranck/asm2c
refs/heads/master
Sources/Parser.swift
mit
1
// // Parser.swift // asm2c // import Foundation import Expression // Proc -> 'Proc' Label ProcPrimaryExpression Label 'Endp' // ProcPrimaryExpression = Line | ProcPrimaryExpression Line // // DataLine -> Label DataSymbol DataPrimaryExpression | DataSymbol DataPrimaryExpression // DataPrimaryExpression -> PrimaryExpression | DataPrimaryExpression ',' PrimaryExpression // // // | Number 'dup' '(' Expression ')' // // // DataSymbol -> 'db' | 'dw' | 'dd' // // Expression -> PrimaryExpression Operator Expression | PrimaryExpression // | Operator PrimaryExpression // PrimaryExpression -> Identifier | Number | '(' Expression ')' | Registry | DataString | '[' Expression ']' // // Operator -> '*' | '/' | '+' | '-' | offset // // // simplified version of pointer: // // Pointeur -> Identifier | Identifier Operator OffsetExpression | '[' Pointeur ']' // OffsetExpression -> PrimaryOffsetExpression | PrimaryOffsetExpression Operator OffsetExpression // PrimaryOffsetExpression -> Number | '(' OffsetExpression ')' // // // // Line -> // Instruction1Line | Instruction2Line | JmpInstructionLine | LabelLine | DataLine | Instruction0Line // // Instruction0Line -> 'Ret' // // Instruction1Line -> // <instruction 1> Qualifier? Expression // // Instruction2 -> // Instruction2Token Qualifier? Expression Comma Expression // // Call -> // CallToken Label // // JmpInstruction -> // JumpInstructionToken Label // // Expression -> // PrimaryExpression Operator Expression | PrimaryExpression // // PrimaryExpression -> Identifier | Number | Variable | Register | ( Expression ) | [ Expression] | Offset [ Expression] | Label enum Errors: Error { case WrongExpressionBeforeDup case UnexpectedToken case UnexpectedToken2(Token) case UndefinedOperator(String) case UnexpectedRegister(String) case ExpectedCharacter(Character) case ExpectedExpression case ExpectedToken(Token) case ExpectedKeyword(String) case ExpectedArgumentList case ExpectedFunctionName case ExpectedInstruction case ExpectedRegister case ErrorParsing(String) } class Parser { let defaultSelector: String = "ds" var labelsnoCase = true let tokens: [(Token,Int, String)] var equ = [equNode]() var errorNumber = 0 var index = 0 var dummyIndex = 0 var line = 0 //var currentSizeDirective: SizeDirective = .unknown var currentSelector: String init(tokens: [(Token,Int, String)]) { self.tokens = tokens self.currentSelector = defaultSelector } func peekCurrentToken() -> Token { if index >= tokens.count { return .EOF } return tokens[index].0 } func peekCurrentTokenLineNumber() -> Int? { if index >= tokens.count { return nil } return tokens[index].1 } func currentLineNumber() -> Int { if index >= tokens.count { return 9999999 } return tokens[index].1 } func popCurrentToken() -> Token { if index >= tokens.count { return .EOF } let token = tokens[index] index = index + 1 return token.0 } func parseNumber() throws -> ExprNode { guard case let Token.Number(value) = popCurrentToken() else { throw Errors.UnexpectedToken } return NumberNode(value: value) } func parseRegister() throws -> RegisterNode { switch popCurrentToken() { case Token.Register( let value): return RegisterNode(value: value.lowercased(), size: .dword, isH: false) case Token.Register16(let value): switch value.lowercased() { case "ax": return RegisterNode(value: "eax", size: .word, isH: false) case "bx": return RegisterNode(value: "ebx", size: .word, isH: false) case "cx": return RegisterNode(value: "ecx", size: .word, isH: false) case "dx": return RegisterNode(value: "edx", size: .word, isH: false) case "si": return RegisterNode(value: "esi", size: .word, isH: false) case "di": return RegisterNode(value: "edi", size: .word, isH: false) case "bp": return RegisterNode(value: "ebp", size: .word, isH: false) case "cs": return RegisterNode(value: "cs", size: .word, isH: false) case "ds": return RegisterNode(value: "ds", size: .word, isH: false) case "es": return RegisterNode(value: "es", size: .word, isH: false) case "fs": return RegisterNode(value: "fs", size: .word, isH: false) case "gs": return RegisterNode(value: "gs", size: .word, isH: false) case "ss": return RegisterNode(value: "ss", size: .word, isH: false) default: throw Errors.UnexpectedRegister(value) // return RegisterNode(value: value.lowercased(), size: .word, isH: false) } case Token.Register8h(let value): switch value.lowercased() { case "ah": return RegisterNode(value: "eax", size: .byte, isH: true) case "bh": return RegisterNode(value: "ebx", size: .byte, isH: true) case "ch": return RegisterNode(value: "ecx", size: .byte, isH: true) case "dh": return RegisterNode(value: "edx", size: .byte, isH: true) default: throw Errors.UnexpectedRegister(value) } case Token.Register8l(let value): switch value.lowercased() { case "al": return RegisterNode(value: "eax", size: .byte, isH: false) case "bl": return RegisterNode(value: "ebx", size: .byte, isH: false) case "cl": return RegisterNode(value: "ecx", size: .byte, isH: false) case "dl": return RegisterNode(value: "edx", size: .byte, isH: false) default: throw Errors.UnexpectedRegister(value) } default: throw Errors.UnexpectedToken } } func parseParens() throws -> ExprNode { guard case Token.ParensOpen = popCurrentToken() else { throw Errors.ExpectedCharacter("(") } guard let exp = try parseExpression() else { throw Errors.ExpectedExpression } guard case Token.ParensClose = popCurrentToken() else { throw Errors.ExpectedCharacter(")") } return ParenthesisNode(node: exp) } func parseBraquet() throws -> ExprNode { guard case Token.BraquetOpen = popCurrentToken() else { throw Errors.ExpectedCharacter("[") } guard let exp = try parseExpression() else { throw Errors.ExpectedExpression } guard case Token.BraquetClose = popCurrentToken() else { throw Errors.ExpectedCharacter("]") } return BraquetNode(expr: exp) } func parseOffset() throws -> ExprNode { guard case Token.Offset = popCurrentToken() else { throw Errors.ExpectedKeyword("Offset") } guard let exp = try parseExpression() else { throw Errors.ExpectedExpression } return OffsetNode(expr: exp) } let operatorPrecedence: [String: Int] = [ "+": 20, "-": 20, "*": 40, "/": 40 ] func getCurrentTokenPrecedence() throws -> Int { guard index < tokens.count else { return -1 } /* guard case .Label = peekCurrentToken() else { return 60 } */ guard case let Token.Operator(op) = peekCurrentToken() else { return -1 } guard let precedence = operatorPrecedence[op] else { throw Errors.UndefinedOperator(op) } return precedence } func parseDataString() throws -> [NumberNode] { var nodes = [NumberNode]() guard case let Token.DataString(value) = popCurrentToken() else { throw Errors.UnexpectedToken } let start = value.index(value.startIndex, offsetBy: 1) let end = value.index(value.endIndex, offsetBy: -1) let myRange:Range = start..<end let stringFound = value.substring(with: myRange) for code in String(stringFound).utf8 { nodes.append(NumberNode(value: Int(code))) } ; if (stringFound.count != nodes.count) { print("Warning string \(stringFound) size!=characters.count\n"); let error="Error string <\(stringFound)> size!=characters.count prob a file encoding issue. (Did you converted your 8bit charset to utfxx?) \n"; print(error) throw Errors.ErrorParsing(error) } return nodes; } func parseDupDataContent() throws -> [ExprNode] { var nodes = [ExprNode]() guard case Token.ParensOpen = popCurrentToken() else { throw Errors.ExpectedToken(.ParensOpen) } let currentLine = currentLineNumber() while (index < tokens.count && currentLine == currentLineNumber()) { switch (peekCurrentToken()) { case Token.ParensClose: _ = popCurrentToken() return nodes; case .Comma: _ = popCurrentToken() default: if let node = try parseExpression() { nodes.append(node) } else { print("error parsing dup inside?") } } } return nodes } func evaluateExpr(expr: ExprNode) -> Int { let expression = Expression("\(expr)") guard let result = try? expression.evaluate() else { print("ERROR: evaluateExpr: \(expr)") //TODO fail properly. return -1 } return Int(result) } func parseDup(dupSize: ExprNode) throws -> [ExprNode] { var evaluateDupsize: Int; var nodes = [ExprNode]() let nodesToCopy = try parseDupDataContent() evaluateDupsize = evaluateExpr(expr: dupSize) for _ in 1...evaluateDupsize { _ = nodesToCopy.map { nodes.append( $0 ) } } return nodes; } func parseExpression() throws -> ExprNode? { switch peekCurrentToken() { case .Operator(_): guard case let Token.Operator(op) = popCurrentToken() else { throw Errors.UnexpectedToken } switch (peekCurrentToken()) { case .Number: return try parseBinaryOp(node: ParenthesisNode (node: BinaryOpNode(op: op, lhs: NumberNode(value: 0), rhs: try parseNumber()))) default: break; } default: break } guard let node = try parsePrimary() else { return nil } return try parseBinaryOp(node: node) } func parsePrimary() throws -> ExprNode? { switch (peekCurrentToken()) { case .Register: return try parseRegister() case .Register16: let node = try parseRegister() guard case .DotDot = peekCurrentToken() else { // to skip cs: es: ds: return node } self.currentSelector = node.value; _ = popCurrentToken() return try parsePrimary() case .Register8h: return try parseRegister() case .Register8l: return try parseRegister() case .Label: return try parseLabel() case .Number: return try parseNumber() case .ParensOpen: return try parseParens() case .BraquetOpen: return try parseBraquet() case .Offset: return try parseOffset() case .DataString: var numberValueSmall = 0 var numberValueBig = 0 let dataString = try parseDataString() var multi = 1 _ = dataString.reversed().map { value -> (NumberNode) in numberValueSmall = numberValueSmall + value.value * multi; multi = multi * 256; return value } multi = 1 _ = dataString.map { value -> (NumberNode) in numberValueBig = numberValueBig + value.value * multi; multi = multi * 256; return value } return quoteNumberNode(valueSmall: numberValueSmall, valueBig: numberValueBig) default: return nil } } func parseBinaryOp(node: ExprNode, exprPrecedence: Int = 0) throws -> ExprNode { var lhs = node while true { let tokenPrecedence = try getCurrentTokenPrecedence() if tokenPrecedence < exprPrecedence { return lhs } guard case let Token.Operator(op) = popCurrentToken() else { throw Errors.UnexpectedToken } guard var rhs = try parsePrimary() else { throw Errors.UnexpectedToken } let nextPrecedence = try getCurrentTokenPrecedence() if tokenPrecedence < nextPrecedence { rhs = try parseBinaryOp(node: rhs, exprPrecedence: tokenPrecedence+1) } lhs = BinaryOpNode(op: op, lhs: lhs, rhs: rhs) } } func parseLabel() throws -> LabelNode { guard case let Token.Label(name) = popCurrentToken() else { throw Errors.UnexpectedToken } if labelsnoCase { return LabelNode(name: name.lowercased()) } else { return LabelNode(name: name) } } func parseDataLine(label: String) throws -> DataPrimaryNode { if case let Token.DataSymbol(symbole) = peekCurrentToken() { _ = popCurrentToken() return try parseDataPrimaryExpression(label: label, dataSymbol: symbole) } throw Errors.UnexpectedToken2(peekCurrentToken()) } func parseDataPrimaryExpression(label: String, dataSymbol: String) throws -> DataPrimaryNode { var nodes = [ExprNode]() // print("xxx line:\(label)") let currentLine = currentLineNumber() while (index < tokens.count && currentLine == currentLineNumber()) { // print("parseDataPrimaryExpression found:\(peekCurrentToken())") switch (peekCurrentToken()) { case .DataString: _ = try parseDataString().map { nodes.append($0) } case .Comma: _ = popCurrentToken() case .Dup: _ = popCurrentToken() if let node = nodes.last { nodes.removeLast() _ = try parseDup(dupSize: node).map { nodes.append($0) } } else { throw Errors.WrongExpressionBeforeDup } case .DataSymbol: return (DataPrimaryNode(name: label, kind: dataSymbol, nodes: nodes)) /* case .Label: print(".Label") return (DataPrimaryNode(name: label, kind: dataSymbol, nodes: nodes)) */ default: if let node = try parseExpression() { nodes.append(node) } else { // print("parseDataPrimaryExpression not processing \(peekCurrentToken()) as data") return (DataPrimaryNode(name: label, kind: dataSymbol, nodes: nodes)) } } } return (DataPrimaryNode(name: label, kind: dataSymbol, nodes: nodes)) } func parseCall() throws -> CallNode { guard case Token.Call = popCurrentToken() else { throw Errors.UnexpectedToken } guard case let Token.Label(name) = popCurrentToken() else { throw Errors.UnexpectedToken } return CallNode(label: name) } func parseJumpInstruction() throws -> JumpInstruction { guard case let Token.JumpInstruction(instruction) = popCurrentToken() else { throw Errors.ExpectedInstruction } guard case let Token.Label(name) = popCurrentToken() else { throw Errors.UnexpectedToken } return JumpInstruction(instruction: instruction, label: name) } func getCurrentSizeDirective() -> SizeDirective { guard case let .Qualifier(name) = peekCurrentToken() else { return .unknown } if let sizeDirective = SizeDirective(rawValue: name.lowercased()) { _ = popCurrentToken() return sizeDirective } else { print("weird sizeDirective: \(name)") return .unknown } } func parseInstruction0() throws -> Instruction0Node { guard case let .Instruction0(instruction) = popCurrentToken() else { throw Errors.ExpectedInstruction } if (instruction.uppercased()=="REP") { guard case let .Instruction0(instructionRep) = popCurrentToken() else { throw Errors.ExpectedInstruction } return Instruction0Node(instruction: "REP_\(instructionRep)") } return Instruction0Node(instruction: instruction) } func parseInstruction1() throws -> Instruction1Node { guard case let Token.Instruction1(instruction) = popCurrentToken() else { throw Errors.ExpectedInstruction } var currentSizeDirective = getCurrentSizeDirective() guard let expr = try parseExpression() else { throw Errors.UnexpectedToken } if currentSizeDirective == .unknown { let currentSizeDirectiveFromExpr: SizeDirective = try getCurrentSizeFrom(expr: expr) currentSizeDirective = currentSizeDirectiveFromExpr } return Instruction1Node(instruction: instruction.uppercased(), sizeDirective: currentSizeDirective, selector: currentSelector, operand: expr) } func isInstructionWithDifferentSizeForSourceAndDestination(instruction : String) -> Bool { if instruction.uppercased() == "MOVSX" { return true } if instruction.uppercased() == "MOVZX" { return true } return false } func parseInstruction2() throws -> Instruction2Node { guard case let Token.Instruction2(instruction) = popCurrentToken() else { throw Errors.ExpectedInstruction } var currentSizeDirectiveDest = getCurrentSizeDirective() var currentSizeDirectiveSource: SizeDirective = .unknown guard let lhs = try parseExpression() else { throw Errors.ExpectedExpression } if currentSizeDirectiveDest == .unknown { let currentSizeDirectiveFromExpr: SizeDirective = try getCurrentSizeFrom(expr: lhs) currentSizeDirectiveDest = currentSizeDirectiveFromExpr } guard case Token.Comma = popCurrentToken() else { throw Errors.UnexpectedToken } currentSizeDirectiveSource = getCurrentSizeDirective() if currentSizeDirectiveDest == .unknown { currentSizeDirectiveDest=currentSizeDirectiveSource } guard var rhs = try parseExpression() else { throw Errors.ExpectedExpression } if instruction.uppercased() == "LEA" { rhs = OffsetNode(expr: rhs) } if let rhs = rhs as? RegisterNode { currentSizeDirectiveSource = rhs.size } if (currentSizeDirectiveSource == .unknown) { currentSizeDirectiveSource = currentSizeDirectiveDest } if (currentSizeDirectiveDest == .unknown) { currentSizeDirectiveDest = currentSizeDirectiveSource } if (isInstructionWithDifferentSizeForSourceAndDestination(instruction: instruction) == true) { if (currentSizeDirectiveDest == currentSizeDirectiveSource) { print("Warning:\(instruction) dest and source size marked as egals, please fix your asm code with a byte ptr or word ptr thing???\n") // TOFIX: Test on DOSBOX if should fail } } return Instruction2Node(instruction: instruction.uppercased(), sizeDirectiveSource: currentSizeDirectiveSource, sizeDirectiveDest: currentSizeDirectiveDest, selector: currentSelector, lhs: lhs, rhs: rhs) } func parseLine() throws -> Any { self.currentSelector = defaultSelector switch peekCurrentToken() { case .Instruction0: return try parseInstruction0() case .Instruction1: return try parseInstruction1() case .Instruction2: return try parseInstruction2() case .JumpInstruction: return try parseJumpInstruction() case .Label: return try parseLabelLine() case .DataSymbol: dummyIndex = dummyIndex + 1 return try parseDataLine(label: "dummy\(dummyIndex)") case .Ret: _ = popCurrentToken() return whateverNode(name: "RET;") case .Call: return try parseCall() default: throw Errors.UnexpectedToken2(peekCurrentToken()) } } // first: main nodes, second: procedures nodes func parseEqu(variableName: String) throws -> ExprNode { if case Token.Equ = peekCurrentToken() { _ = popCurrentToken() guard let equValue = try parseExpression() else { throw Errors.ExpectedExpression } var variableName2 = variableName if labelsnoCase { variableName2 = variableName2.lowercased() } equNameList.append(variableName2) return equNode(name: variableName2, expr: equValue) } throw Errors.UnexpectedToken2(peekCurrentToken()) } func parseLabelLine() throws -> ExprNode { guard case let Token.Label(name) = popCurrentToken() else { throw Errors.UnexpectedToken } if case .DotDot = peekCurrentToken() { _ = popCurrentToken() if labelsnoCase { return GotoLabelNode(name: name.lowercased()) } else { return GotoLabelNode(name: name) } } if case .DataSymbol = peekCurrentToken() { let node = try parseDataLine(label: name) return node } if case .Equ = peekCurrentToken() { return try parseEqu(variableName: name) } if case .Proc = peekCurrentToken() { _ = popCurrentToken() return try parseProcedure(name: name) } throw Errors.UnexpectedToken } func printLine(number lineNumber: Int) { let lineTokens = tokens.filter { $0.1 == lineNumber }.map { $0.0 } let lineString = tokens.filter { $0.1 == lineNumber }.map { $0.2 }.first print("line: <\(lineString)>") print("tokens: <\(lineTokens)>") } func gotoLineAfter(line: Int) { var currentLine = peekCurrentTokenLineNumber() while (currentLine != nil) { if (currentLine! > line) { return } _ = popCurrentToken() currentLine = peekCurrentTokenLineNumber() } } func parseData() -> [DataPrimaryNode] { var data = [DataPrimaryNode]() index = 0 while index < tokens.count { let lineNumber = currentLineNumber() do { switch peekCurrentToken() { case .DataSymbol: dummyIndex = dummyIndex + 1 if let node = try? parseDataLine(label: "dummy\(dummyIndex)") { data.append(node) } case .Label: guard case let Token.Label(name) = popCurrentToken() else { throw Errors.UnexpectedToken } if case .DataSymbol = peekCurrentToken() { var labelName = name if labelsnoCase { labelName = labelName.lowercased() } if let node = try? parseDataLine(label: labelName) { data.append(node) // dataPrimaryNodesMap[node.name] = node } } default: gotoLineAfter(line: lineNumber) break } } catch { gotoLineAfter(line: lineNumber) } } index = 0 return data } func parseProcedure(name: String) throws -> ProcedureNode { var nodes = [Any]() while index < tokens.count { let lineNumber = currentLineNumber() do { //print("parseProcedure parsing <\(peekCurrentToken())>") if case .Endp = peekCurrentToken() { _ = popCurrentToken() break; } let node = try parseLine() if let node = node as? equNode { equ.append(node) } //print("parseProcedure: \(name) adding: \(node)") nodes.append(node) } catch { print("error parsing proc line: \(lineNumber)\n") printLine(number:lineNumber) let lineNumber = currentLineNumber() errorNumber = errorNumber + 1 gotoLineAfter(line: lineNumber) } } //print("parseProcedure: \(name) return: \(nodes)") return ProcedureNode(name: name, nodes:nodes); } func parse() throws -> ([Any],[equNode],Int) { var main = [Any]() index = 0 equ = [] while index < tokens.count { let lineNumber = currentLineNumber() do { let node = try parseLine() if let node = node as? equNode { equ.append(node) } else { main.append(node) } } catch { print("error \(error) parsing line: \(lineNumber)\n") printLine(number:lineNumber) let lineNumber = currentLineNumber() errorNumber = errorNumber + 1 gotoLineAfter(line: lineNumber) } } //main.append(whateverNode(name: "firstRun = 2;goto moveToBackGround;")) return (main,equ,errorNumber) } }
3c2b499f39f0be78524037566f30894e
32.729529
211
0.557971
false
false
false
false
Raureif/WikipediaKit
refs/heads/main
Sources/WikipediaArticleLanguageLink.swift
mit
1
// // WikipediaArticleLanguageLink.swift // WikipediaKit // // Created by Frank Rausch on 2016-07-25. // Copyright © 2017 Raureif GmbH / Frank Rausch // // MIT License // // 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 struct WikipediaArticleLanguageLink { public let language: WikipediaLanguage public let title: String public let url: URL public init(language: WikipediaLanguage, title: String, url: URL) { self.language = language self.title = Wikipedia.sharedFormattingDelegate?.format(context: .articleTitle, rawText: title, title: title, language: language, isHTML: false) ?? title self.url = url } } extension WikipediaArticleLanguageLink { init?(jsonDictionary dict: JSONDictionary) { guard let languageCode = dict["lang"] as? String, let localizedName = dict["langname"] as? String, let autonym = dict["autonym"] as? String, let title = dict["title"] as? String, // TODO: Can we also get the display title here? let urlString = dict["url"] as? String, let url = URL(string: urlString) else { return nil } if !WikipediaLanguage.isUnsupported(languageCode: languageCode) { let language = WikipediaLanguage(code: languageCode, localizedName: localizedName, autonym: autonym) self.init(language: language, title: title, url: url) } else { return nil } } }
3510e64af74f78a9f49747d0b7165ca7
40.080645
161
0.692972
false
false
false
false
YotrolZ/PullToMakeFlight
refs/heads/master
PullToMakeFlight/PullToRefresh/PullToRefresh.swift
mit
5
// // PullToRefresh.swift // CookingPullToRefresh // // Created by Anastasiya Gorban on 4/14/15. // Copyright (c) 2015 Yalantis. All rights reserved. // import UIKit import Foundation public protocol RefreshViewAnimator { func animateState(state: State) } // MARK: PullToRefresh public class PullToRefresh: NSObject { let refreshView: UIView var action: (() -> ())? private let animator: RefreshViewAnimator // MARK: - ScrollView & Observing private var scrollViewDefaultInsets = UIEdgeInsetsZero weak var scrollView: UIScrollView? { didSet { oldValue?.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &KVOContext) if let scrollView = scrollView { scrollViewDefaultInsets = scrollView.contentInset addScrollViewObserving() } } } private func addScrollViewObserving() { scrollView?.addObserver(self, forKeyPath: contentOffsetKeyPath, options: .Initial, context: &KVOContext) } private func removeScrollViewObserving() { scrollView?.removeObserver(self, forKeyPath: contentOffsetKeyPath, context: &KVOContext) } // MARK: - State var state: State = .Inital { didSet { animator.animateState(state) switch state { case .Loading: if let scrollView = scrollView where (oldValue != .Loading) { scrollView.contentOffset = previousScrollViewOffset scrollView.bounces = false UIView.animateWithDuration(0.3, animations: { let insets = self.refreshView.frame.height + self.scrollViewDefaultInsets.top scrollView.contentInset.top = insets scrollView.contentOffset = CGPointMake(scrollView.contentOffset.x, -insets) }, completion: { finished in scrollView.bounces = true }) action?() } case .Finished: removeScrollViewObserving() UIView.animateWithDuration(1, delay: 0.2, usingSpringWithDamping: 0.4, initialSpringVelocity: 0.8, options: UIViewAnimationOptions.CurveLinear, animations: { self.scrollView?.contentInset = self.scrollViewDefaultInsets self.scrollView?.contentOffset.y = -self.scrollViewDefaultInsets.top }, completion: { finished in self.addScrollViewObserving() self.state = .Inital }) default: break } } } // MARK: - Initialization public init(refreshView: UIView, animator: RefreshViewAnimator) { self.refreshView = refreshView self.animator = animator } public override convenience init() { let refreshView = DefaultRefreshView() self.init(refreshView: refreshView, animator: DefaultViewAnimator(refreshView: refreshView)) } deinit { removeScrollViewObserving() } // MARK: KVO private var KVOContext = "PullToRefreshKVOContext" private let contentOffsetKeyPath = "contentOffset" private var previousScrollViewOffset: CGPoint = CGPointZero override public func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<()>) { if (context == &KVOContext && keyPath == contentOffsetKeyPath && object as? UIScrollView == scrollView) { let offset = previousScrollViewOffset.y + scrollViewDefaultInsets.top let refreshViewHeight = refreshView.frame.size.height switch offset { case 0: state = .Inital case -refreshViewHeight...0 where (state != .Loading && state != .Finished): state = .Releasing(progress: -offset / refreshViewHeight) case -1000...(-refreshViewHeight): if state == State.Releasing(progress: 1) && scrollView?.dragging == false { state = .Loading } else if state != State.Loading && state != State.Finished { state = .Releasing(progress: -offset / refreshViewHeight) } default: break } } previousScrollViewOffset.y = scrollView!.contentOffset.y } // MARK: - Start/End Refreshing func startRefreshing() { if self.state != State.Inital { return } scrollView?.setContentOffset(CGPointMake(0, -refreshView.frame.height - scrollViewDefaultInsets.top), animated: true) let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(0.27 * Double(NSEC_PER_SEC))) dispatch_after(delayTime, dispatch_get_main_queue(), { self.state = State.Loading }) } func endRefreshing() { if state == .Loading { state = .Finished } } } // MARK: - State enumeration public enum State:Equatable, Printable { case Inital, Loading, Finished case Releasing(progress: CGFloat) public var description: String { switch self { case .Inital: return "Inital" case .Releasing(let progress): return "Releasing:\(progress)" case .Loading: return "Loading" case .Finished: return "Finished" } } } public func ==(a: State, b: State) -> Bool { switch (a, b) { case (.Inital, .Inital): return true case (.Loading, .Loading): return true case (.Finished, .Finished): return true case (.Releasing(let a), .Releasing(let b)): return true default: return false } } // MARK: Default PullToRefresh class DefaultRefreshView: UIView { private(set) var activicyIndicator: UIActivityIndicatorView! override init(frame: CGRect) { super.init(frame: frame) commonInit() } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } private func commonInit() { frame = CGRectMake(frame.origin.x, frame.origin.y, frame.width, 40) } override func layoutSubviews() { if (activicyIndicator == nil) { activicyIndicator = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.Gray) activicyIndicator.center = convertPoint(center, fromView: superview) activicyIndicator.hidesWhenStopped = false addSubview(activicyIndicator) } super.layoutSubviews() } override func willMoveToSuperview(newSuperview: UIView?) { super.willMoveToSuperview(newSuperview) if let superview = newSuperview { frame = CGRectMake(frame.origin.x, frame.origin.y, superview.frame.width, 40) } } } class DefaultViewAnimator: RefreshViewAnimator { private let refreshView: DefaultRefreshView init(refreshView: DefaultRefreshView) { self.refreshView = refreshView } func animateState(state: State) { switch state { case .Inital: refreshView.activicyIndicator?.stopAnimating() case .Releasing(let progress): var transform = CGAffineTransformIdentity transform = CGAffineTransformScale(transform, progress, progress); transform = CGAffineTransformRotate(transform, 3.14 * progress * 2); refreshView.activicyIndicator.transform = transform case .Loading: refreshView.activicyIndicator.startAnimating() default: break } } }
d43350b9916284e9356a1228edf211b8
33.008658
173
0.603233
false
false
false
false
mtransitapps/mtransit-for-ios
refs/heads/master
MonTransit/Source/UI/CustomControl/StopImageView.swift
apache-2.0
1
import UIKit class StopImageView: UIView { func addBusNumber(iBusNumber:String, iDirection:String) { if iBusNumber == "" { let wImage:UIImageView = UIImageView(frame: CGRect(x: 6, y: 6, width: self.frame.size.width - 12, height: self.frame.size.height - 12)) wImage.image = UIImage(named: "subway_icn") wImage.contentMode = UIViewContentMode.ScaleAspectFill self.insertSubview(wImage, atIndex: 1) } else { let headerLabel:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.frame.size.width, height: self.frame.size.height - 10)) headerLabel.contentMode = UIViewContentMode.ScaleAspectFill headerLabel.textColor = UIColor.whiteColor() headerLabel.textAlignment = NSTextAlignment.Center headerLabel.text = iBusNumber headerLabel.font = UIFont.boldSystemFontOfSize(30.0) self.insertSubview(headerLabel, atIndex: 1) } let directionLabel:UILabel = UILabel(frame: CGRect(x: 2, y: self.frame.origin.y - 33, width: self.frame.size.width - 2, height: 20)) directionLabel.contentMode = UIViewContentMode.ScaleAspectFill directionLabel.textColor = UIColor.whiteColor() directionLabel.backgroundColor = UIColor.blackColor() directionLabel.alpha = 0.5 directionLabel.textAlignment = NSTextAlignment.Center directionLabel.text = iDirection directionLabel.font = UIFont.boldSystemFontOfSize(10.0) self.insertSubview(directionLabel, atIndex: 2) } override func awakeFromNib() { self.layer.cornerRadius = 10.0 self.layer.borderColor = UIColor.whiteColor().CGColor self.layer.borderWidth = 3.0 } }
4d1a32cc7a1c9b55c00e61883a71ca28
42.853659
147
0.655172
false
false
false
false
zigdanis/Interactive-Transitioning
refs/heads/master
MyPlayground.playground/Sources/RoundedImageView.swift
mit
1
// // RoundedView.swift // InteractiveTransitioning // // Created by Danis Ziganshin on 24/07/16. // Copyright © 2016 Zigdanis. All rights reserved. // import UIKit @IBDesignable public class RoundedImageView: UIImageView, CAAnimationDelegate { let maskLayer = CAShapeLayer() let borderCircle = CAShapeLayer() var expandedRect: CGRect? = nil public var animationCompletion: (()->())? convenience init() { self.init(image: nil) } override convenience init(frame: CGRect) { self.init(image: UIImage(named: "close-winter")) } public override init(image: UIImage?) { super.init(image: image) setupViewBehaviour() addRoundingLayers() } public required init?(coder: NSCoder) { super.init(coder:coder) setupViewBehaviour() addRoundingLayers() } func setupViewBehaviour() { clipsToBounds = true translatesAutoresizingMaskIntoConstraints = false contentMode = .scaleAspectFill } override public func layoutSubviews() { updateRoundedLayers(for: expandedRect) super.layoutSubviews() } public override func prepareForInterfaceBuilder() { updateRoundedLayers() super.prepareForInterfaceBuilder() } //MARK: - Logic func addRoundingLayers() { borderCircle.borderColor = UIColor.white.cgColor borderCircle.borderWidth = 2 layer.addSublayer(borderCircle) maskLayer.fillColor = UIColor.white.cgColor maskLayer.lineWidth = 0 layer.mask = maskLayer updateRoundedLayers() } func updateRoundedLayers(for rect: CGRect? = nil) { let aBounds = rect ?? bounds let minSide = min(aBounds.width, aBounds.height) let x = aBounds.midX - minSide/2 let y = aBounds.midY - minSide/2 let squareInCenter = CGRect(x: x, y: y, width: minSide, height: minSide) borderCircle.frame = squareInCenter borderCircle.cornerRadius = minSide / 2 let arcPath = CGPath(ellipseIn: squareInCenter, transform: nil) maskLayer.path = arcPath maskLayer.bounds = aBounds maskLayer.position = CGPoint(x: aBounds.midX, y: aBounds.midY) } //MARK: - Public public func animateImageViewWithExpand(initial: CGRect, destination: CGRect, duration: TimeInterval, options: UIViewAnimationOptions = []) { let minInitialSide = min(initial.width, initial.height) let minDestinationSide = min(destination.width, destination.height) let squareInitial = CGRect(x: 0, y: 0, width: minInitialSide, height: minInitialSide) let squareDestination = CGRect(x: 0, y: 0, width: minDestinationSide, height: minDestinationSide) let squareExpanded = containingCircleRect(for: destination) let minExpandedSide = squareExpanded.size.width let timingFunc = mediaTimingFunction(for: options) let fullDuration = duration + duration / 20.0 let firstPart = NSNumber(value: 0) let secondPart = NSNumber(value: duration / fullDuration) let lastPart = NSNumber(value: 1) let boundsAnimation = CAKeyframeAnimation(keyPath: "bounds") let boundsAnimationFromValue = NSValue(cgRect: squareInitial) let boundsAnimationToValue = NSValue(cgRect: squareDestination) let boundsAnimationExValue = NSValue(cgRect: squareExpanded) boundsAnimation.values = [ boundsAnimationFromValue, boundsAnimationToValue, boundsAnimationExValue ] boundsAnimation.timingFunctions = [ timingFunc, timingFunc] boundsAnimation.keyTimes = [firstPart, secondPart, lastPart] boundsAnimation.duration = fullDuration let positionAnimation = CAKeyframeAnimation(keyPath: "position") let fromPosition = CGPoint(x: initial.midX, y: initial.midY) let toPosition = CGPoint(x: destination.midX, y: destination.midY) positionAnimation.values = [ NSValue(cgPoint: fromPosition), NSValue(cgPoint: toPosition), NSValue(cgPoint: toPosition) ] positionAnimation.timingFunctions = [ timingFunc, timingFunc ] positionAnimation.keyTimes = [firstPart, secondPart, lastPart] positionAnimation.duration = fullDuration let cornersAnimation = CAKeyframeAnimation(keyPath: "cornerRadius") cornersAnimation.values = [ minInitialSide / 2, minDestinationSide / 2, minExpandedSide / 2 ] cornersAnimation.timingFunctions = [ timingFunc, timingFunc ] cornersAnimation.keyTimes = [firstPart, secondPart, lastPart] cornersAnimation.duration = fullDuration let pathAnimation = CAKeyframeAnimation(keyPath: "path") let fromPath = CGPath(ellipseIn: squareInitial, transform: nil) let toPath = CGPath(ellipseIn: squareDestination, transform: nil) let exPath = CGPath(ellipseIn: squareExpanded, transform: nil) pathAnimation.values = [ fromPath, toPath, exPath ] pathAnimation.timingFunctions = [ timingFunc, timingFunc ] pathAnimation.keyTimes = [firstPart, secondPart, lastPart] pathAnimation.duration = fullDuration let borderGroup = CAAnimationGroup() borderGroup.duration = fullDuration borderGroup.animations = [boundsAnimation, positionAnimation, cornersAnimation] let maskGroup = CAAnimationGroup() maskGroup.delegate = self maskGroup.duration = fullDuration maskGroup.animations = [boundsAnimation, positionAnimation, pathAnimation] borderCircle.cornerRadius = minExpandedSide / 2 borderCircle.add(borderGroup, forKey: "Resizing border") maskLayer.path = exPath maskLayer.bounds = squareExpanded maskLayer.position = toPosition maskLayer.add(maskGroup, forKey: "Resizing circle mask") expandedRect = squareExpanded } //MARK: - CAAnimation Delegate public func animationDidStop(_ anim: CAAnimation, finished flag: Bool) { animationCompletion?() } //MARK: - Helpers func setupOptionsForAnimation(animation: CAAnimationGroup, options: UIViewAnimationOptions) { animation.timingFunction = self.mediaTimingFunction(for: options) if options.contains(.autoreverse) { animation.autoreverses = true } if options.contains(.repeat) { animation.repeatCount = MAXFLOAT } } func mediaTimingFunction(for options: UIViewAnimationOptions) -> CAMediaTimingFunction { var functionName = kCAMediaTimingFunctionLinear if options.contains(.curveLinear) { functionName = kCAMediaTimingFunctionLinear } else if options.contains(.curveEaseIn) { functionName = kCAMediaTimingFunctionEaseIn } else if options.contains(.curveEaseOut) { functionName = kCAMediaTimingFunctionEaseOut } else if options.contains(.curveEaseInOut) { functionName = kCAMediaTimingFunctionEaseInEaseOut } return CAMediaTimingFunction(name: functionName) } func containingCircleRect(for rect: CGRect) -> CGRect { let height = rect.height let width = rect.width let diameter = sqrt((height * height) + (width * width)) let newX = rect.origin.x - (diameter - width) / 2 let newY = rect.origin.y - (diameter - height) / 2 let containerRect = CGRect(x: newX, y: newY, width: diameter, height: diameter) return containerRect } }
17007659ca3d2dc697a437da9563c1f0
39.054187
144
0.631288
false
false
false
false
aguptaadco/cordoba-plugin-iosrtc
refs/heads/master
src/PluginMediaStreamTrack.swift
mit
1
import Foundation class PluginMediaStreamTrack : NSObject, RTCMediaStreamTrackDelegate { var rtcMediaStreamTrack: RTCMediaStreamTrack var id: String var kind: String var eventListener: ((data: NSDictionary) -> Void)? var eventListenerForEnded: (() -> Void)? var lostStates = Array<String>() init(rtcMediaStreamTrack: RTCMediaStreamTrack) { NSLog("PluginMediaStreamTrack#init()") self.rtcMediaStreamTrack = rtcMediaStreamTrack self.id = rtcMediaStreamTrack.label // NOTE: No "id" property provided. self.kind = rtcMediaStreamTrack.kind } deinit { NSLog("PluginMediaStreamTrack#deinit()") } func run() { NSLog("PluginMediaStreamTrack#run() [kind:\(self.kind), id:\(self.id)]") self.rtcMediaStreamTrack.delegate = self } func getJSON() -> NSDictionary { return [ "id": self.id, "kind": self.kind, "label": self.rtcMediaStreamTrack.label, "enabled": self.rtcMediaStreamTrack.isEnabled() ? true : false, "readyState": PluginRTCTypes.mediaStreamTrackStates[self.rtcMediaStreamTrack.state().rawValue] as String! ] } func setListener( eventListener: (data: NSDictionary) -> Void, eventListenerForEnded: () -> Void ) { NSLog("PluginMediaStreamTrack#setListener() [kind:\(self.kind), id:\(self.id)]") self.eventListener = eventListener self.eventListenerForEnded = eventListenerForEnded for readyState in self.lostStates { self.eventListener!(data: [ "type": "statechange", "readyState": readyState, "enabled": self.rtcMediaStreamTrack.isEnabled() ? true : false ]) if readyState == "ended" { self.eventListenerForEnded!() } } self.lostStates.removeAll() } func setEnabled(value: Bool) { NSLog("PluginMediaStreamTrack#setEnabled() [kind:\(self.kind), id:\(self.id), value:\(value)]") self.rtcMediaStreamTrack.setEnabled(value) } // TODO: No way to stop the track. // Check https://github.com/eface2face/cordova-plugin-iosrtc/issues/140 func stop() { NSLog("PluginMediaStreamTrack#stop() [kind:%@, id:%@]", String(self.kind), String(self.id)) NSLog("PluginMediaStreamTrack#stop() | stop() not implemented (see: https://github.com/eface2face/cordova-plugin-iosrtc/issues/140") // NOTE: There is no setState() anymore // self.rtcMediaStreamTrack.setState(RTCTrackStateEnded) // Let's try setEnabled(false), but it also fails. self.rtcMediaStreamTrack.setEnabled(false) } /** * Methods inherited from RTCMediaStreamTrackDelegate. */ func mediaStreamTrackDidChange(rtcMediaStreamTrack: RTCMediaStreamTrack!) { let state_str = PluginRTCTypes.mediaStreamTrackStates[self.rtcMediaStreamTrack.state().rawValue] as String! NSLog("PluginMediaStreamTrack | state changed [kind:\(self.kind), id:\(self.id), state:\(state_str), enabled:\(self.rtcMediaStreamTrack.isEnabled() ? true : false)]") if self.eventListener != nil { self.eventListener!(data: [ "type": "statechange", "readyState": state_str, "enabled": self.rtcMediaStreamTrack.isEnabled() ? true : false ]) if self.rtcMediaStreamTrack.state().rawValue == RTCTrackStateEnded.rawValue { self.eventListenerForEnded!() } } else { // It may happen that the eventListener is not yet set, so store the lost states. self.lostStates.append(state_str) } } }
c18d44908d0c211f824e18dac2dc66e0
28.421053
168
0.70155
false
false
false
false
mitchellporter/SAInboxViewController
refs/heads/master
SAInboxViewController/SAInboxTransitioningContainerView.swift
mit
1
// // SAInboxTransitioningContainerView.swift // SAInboxViewController // // Created by Taiki Suzuki on 2015/08/15. // Copyright (c) 2015年 Taiki Suzuki. All rights reserved. // import UIKit class SAInboxTransitioningContainerView: UIView { //MARK: - Inner Structs private struct ImageInformation { enum Position { case Below, Above, Target } let tag: Int let initialOrigin: CGPoint let height: CGFloat let isTarget: Bool let position: Position } //MARK: - Instance Properties private var imageInformations: [ImageInformation] = [] private(set) var targetPosition: CGPoint? private(set) var targetHeight: CGFloat? private(set) var headerImageView = UIImageView() var headerImage: UIImage? { set { headerImageView.image = newValue headerImageView.frame.size = CGSize(width: frame.size.width, height: 64) addSubview(headerImageView) } get { return headerImageView.image } } var headerViewOrigin: CGPoint = CGPointZero init() { super.init(frame: CGRectZero) backgroundColor = .clearColor() } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } //MARK: - Internal Methods extension SAInboxTransitioningContainerView { func setupContainer(targetCell: UITableViewCell, cells: [UITableViewCell], superview: UIView) { var imageTag: Int = 10001 var detectTarget = false for cell in cells { if let point = cell.superview?.convertPoint(cell.frame.origin, toView: superview) { let isTarget: Bool if targetCell == cell { isTarget = true detectTarget = true targetPosition = point targetHeight = CGRectGetHeight(cell.frame) } else { isTarget = false } let position: ImageInformation.Position if isTarget { position = .Target } else if !detectTarget { position = .Below } else { position = .Above } let imageView = UIImageView(frame: cell.bounds) cell.selectionStyle = .None imageView.image = cell.screenshotImage() cell.selectionStyle = .Default imageView.tag = imageTag imageView.frame.origin = point addSubview(imageView) imageInformations += [ImageInformation(tag: imageTag++, initialOrigin: point, height: CGRectGetHeight(cell.frame), isTarget: isTarget, position: position)] } } } func resetContainer() { if let views = subviews as? [UIView] { for view in views { view.removeFromSuperview() } } imageInformations.removeAll(keepCapacity: false) targetPosition = nil } func open() { if let targetPosition = targetPosition { for imageInformation in imageInformations { let view = viewWithTag(imageInformation.tag) if imageInformation.isTarget { view?.alpha = 0 } if imageInformation.initialOrigin.y <= targetPosition.y { view?.frame.origin.y = imageInformation.initialOrigin.y - targetPosition.y } else { view?.frame.origin.y = frame.size.height + (imageInformation.initialOrigin.y - targetPosition.y) - imageInformation.height } } } } func close() { for imageInformation in imageInformations { let view = viewWithTag(imageInformation.tag) if imageInformation.isTarget { view?.alpha = 1 } view?.frame.origin.y = imageInformation.initialOrigin.y } } func upperMoveToValue(value: CGFloat) { for imageInformation in imageInformations { if let targetPosition = targetPosition where targetPosition.y >= imageInformation.initialOrigin.y { viewWithTag(imageInformation.tag)?.frame.origin.y = imageInformation.initialOrigin.y - targetPosition.y + value } } } func lowerMoveToValue(value: CGFloat) { for imageInformation in imageInformations { if let targetPosition = targetPosition where targetPosition.y < imageInformation.initialOrigin.y { viewWithTag(imageInformation.tag)?.frame.origin.y = frame.size.height + (imageInformation.initialOrigin.y - targetPosition.y) - imageInformation.height - value } } } }
af4e8e782c2e400e5bb0297efb3f2461
33.713287
175
0.571716
false
false
false
false
NextFaze/FazeKit
refs/heads/master
FazeKit/Classes/CodableAdditions.swift
apache-2.0
2
// // CodableAdditions.swift // FazeKit // // Created by Shane Woolcock on 4/10/19. // import Foundation import UIKit // Taken from: https://stackoverflow.com/questions/44603248/how-to-decode-a-property-with-type-of-json-dictionary-in-swift-4-decodable-proto public struct JSONCodingKeys: CodingKey { public var stringValue: String public init?(stringValue: String) { self.stringValue = stringValue } public var intValue: Int? public init?(intValue: Int) { self.init(stringValue: "\(intValue)") self.intValue = intValue } } public extension KeyedDecodingContainer { func decode(_ type: [String: Any].Type, forKey key: K) throws -> [String: Any] { let container = try self.nestedContainer(keyedBy: JSONCodingKeys.self, forKey: key) return try container.decode(type) } func decodeIfPresent(_ type: [String: Any].Type, forKey key: K) throws -> [String: Any]? { guard self.contains(key) else { return nil } guard try self.decodeNil(forKey: key) == false else { return nil } return try self.decode(type, forKey: key) } func decode(_ type: [Any].Type, forKey key: K) throws -> [Any] { var container = try self.nestedUnkeyedContainer(forKey: key) return try container.decode(type) } func decodeIfPresent(_ type: [Any].Type, forKey key: K) throws -> [Any]? { guard self.contains(key) else { return nil } guard try self.decodeNil(forKey: key) == false else { return nil } return try self.decode(type, forKey: key) } func decode(_ type: [String: Any].Type) throws -> [String: Any] { var dictionary = [String: Any]() for key in self.allKeys { if let boolValue = try? self.decode(Bool.self, forKey: key) { dictionary[key.stringValue] = boolValue } else if let stringValue = try? self.decode(String.self, forKey: key) { dictionary[key.stringValue] = stringValue } else if let intValue = try? self.decode(Int.self, forKey: key) { dictionary[key.stringValue] = intValue } else if let doubleValue = try? self.decode(Double.self, forKey: key) { dictionary[key.stringValue] = doubleValue } else if let nestedDictionary = try? self.decode([String: Any].self, forKey: key) { dictionary[key.stringValue] = nestedDictionary } else if let nestedArray = try? self.decode([Any].self, forKey: key) { dictionary[key.stringValue] = nestedArray } } return dictionary } } public extension UnkeyedDecodingContainer { mutating func decode(_ type: [Any].Type) throws -> [Any] { var array: [Any] = [] while self.isAtEnd == false { // See if the current value in the JSON array is `null` first and prevent infite recursion with nested arrays. if try self.decodeNil() { continue } else if let value = try? self.decode(Bool.self) { array.append(value) } else if let value = try? self.decode(Double.self) { array.append(value) } else if let value = try? self.decode(Int.self) { array.append(value) } else if let value = try? self.decode(String.self) { array.append(value) } else if let nestedDictionary = try? self.decode([String: Any].self) { array.append(nestedDictionary) } else if var nestedContainer = try? self.nestedUnkeyedContainer(), let nestedArray = try? nestedContainer.decode([Any].self) { array.append(nestedArray) } } return array } mutating func decode(_ type: [String: Any].Type) throws -> [String: Any] { let nestedContainer = try self.nestedContainer(keyedBy: JSONCodingKeys.self) return try nestedContainer.decode(type) } } // extra convenience funcs public extension KeyedDecodingContainer { func decode(_ type: UIColor.Type, forKey key: K) throws -> UIColor { let colorString = try self.decode(String.self, forKey: key) return UIColor(hexString: colorString) } func decodeIfPresent(_ type: UIColor.Type, forKey key: K) throws -> UIColor? { guard let colorString = try self.decodeIfPresent(String.self, forKey: key) else { return nil } return UIColor(hexString: colorString) } func decodeEnum<T: RawRepresentable>(_ type: T.Type, forKey key: K) throws -> T where T.RawValue == String { let stringValue = try self.decode(String.self, forKey: key) guard let enumValue = T(rawValue: stringValue) else { throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "Unknown enum case \(String(describing: T.self)).\(stringValue)") } return enumValue } func decodeEnumIfPresent<T: RawRepresentable>(_ type: T.Type, forKey key: K) throws -> T? where T.RawValue == String { guard let stringValue = try self.decodeIfPresent(String.self, forKey: key) else { return nil } guard let enumValue = T(rawValue: stringValue) else { throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "Unknown enum case \(String(describing: T.self)).\(stringValue)") } return enumValue } func decodeEnum<T: RawRepresentable>(_ type: T.Type, forKey key: K) throws -> T where T.RawValue == Int { let intValue = try self.decode(Int.self, forKey: key) guard let enumValue = T(rawValue: intValue) else { throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "Unknown enum case \(String(describing: T.self)).\(intValue)") } return enumValue } func decodeEnumIfPresent<T: RawRepresentable>(_ type: T.Type, forKey key: K) throws -> T? where T.RawValue == Int { guard let intValue = try self.decodeIfPresent(Int.self, forKey: key) else { return nil } guard let enumValue = T(rawValue: intValue) else { throw DecodingError.dataCorruptedError(forKey: key, in: self, debugDescription: "Unknown enum case \(String(describing: T.self)).\(intValue)") } return enumValue } } public extension KeyedEncodingContainer { mutating func encode(_ value: UIColor, forKey key: K) throws { try self.encode(value.hexStringRGB, forKey: key) } mutating func encodeIfPresent(_ value: UIColor?, forKey key: K) throws { try self.encodeIfPresent(value?.hexStringRGB, forKey: key) } mutating func encodeEnum<T: RawRepresentable>(_ value: T, forKey key: K) throws where T.RawValue == String { try self.encode(value.rawValue, forKey: key) } mutating func encodeEnumIfPresent<T: RawRepresentable>(_ value: T?, forKey key: K) throws where T.RawValue == String { try self.encodeIfPresent(value?.rawValue, forKey: key) } mutating func encodeEnum<T: RawRepresentable>(_ value: T, forKey key: K) throws where T.RawValue == Int { try self.encode(value.rawValue, forKey: key) } mutating func encodeEnumIfPresent<T: RawRepresentable>(_ value: T?, forKey key: K) throws where T.RawValue == Int { try self.encodeIfPresent(value?.rawValue, forKey: key) } mutating func encode(_ value: [String: Any], forKey key: K) throws { var container = self.nestedContainer(keyedBy: JSONCodingKeys.self, forKey: key) try encodeDict(value, into: &container) } mutating func encodeIfPresent(_ value: [String: Any]?, forKey key: K) throws { guard let value = value else { return } try self.encode(value, forKey: key) } mutating func encode(_ value: [Any], forKey key: K) throws { var container = self.nestedUnkeyedContainer(forKey: key) try container.encode(value) } mutating func encodeIfPresent(_ value: [Any]?, forKey key: K) throws { guard let value = value else { return } try self.encode(value, forKey: key) } } public extension UnkeyedEncodingContainer { mutating func encode(_ value: [Any]) throws { try value.forEach { element in guard element as Any? != nil else { return } switch element { case let element as Bool: try self.encode(element) case let element as Double: try self.encode(element) case let element as Int: try self.encode(element) case let element as String: try self.encode(element) case let element as [String: Any]: try self.encode(element) case let element as [Any]: var nestedContainer = self.nestedUnkeyedContainer() try nestedContainer.encode(element) default: break } } } mutating func encode(_ value: [String: Any]) throws { var nestedContainer = self.nestedContainer(keyedBy: JSONCodingKeys.self) try encodeDict(value, into: &nestedContainer) } } private func encodeDict(_ value: [String: Any], into container: inout KeyedEncodingContainer<JSONCodingKeys>) throws { try value.forEach { (key, val) in guard let key = JSONCodingKeys(stringValue: key) else { return } switch val { case let val as Bool: try container.encode(val, forKey: key) case let val as Double: try container.encode(val, forKey: key) case let val as Int: try container.encode(val, forKey: key) case let val as String: try container.encode(val, forKey: key) case let val as [String: Any]: try container.encode(val, forKey: key) case let val as [Any]: var nestedContainer = container.nestedUnkeyedContainer(forKey: key) try nestedContainer.encode(val) default: break } } }
df673864d7bd7fc09f0e782fe14de13d
39.442688
157
0.616302
false
false
false
false
kingslay/KSJSONHelp
refs/heads/master
Example/Tests/TestStruct.swift
mit
1
// // TestStruct.swift // KSJSONHelp // // Created by king on 16/5/7. // Copyright © 2016年 king. All rights reserved. // import XCTest import KSJSONHelp struct StructTestModel: Storable,Model { var pointId: Int64? var title: String? var favorite: Bool init() { favorite = false } func setValue(_ value: Any?, forKey key: String) { } } class TestStruct: SQLiteTestCase { func testSave() { let berlin = StructTestModel() berlin.save() let object = StructTestModel.fetch(nil)![0] object.favorite assert(object.favorite == berlin.favorite) } }
deac6328a7b5a43421aa4ba4eda6b66b
18.787879
54
0.601838
false
true
false
false
nmdias/FeedKit
refs/heads/master
Example macOS/ViewController.swift
mit
1
// // ViewController.swift // // Copyright (c) 2016 - 2018 Nuno Manuel Dias // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // import Cocoa import FeedKit let feedURL = URL(string: "http://images.apple.com/main/rss/hotnews/hotnews.rss")! class ViewController: NSViewController { @IBOutlet weak var feedTableView: NSTableView! @IBOutlet weak var feedItemsTableView: NSTableView! @IBOutlet var textView: NSTextView! var feed: RSSFeed? override func viewDidLoad() { super.viewDidLoad() let parser = FeedParser(URL: feedURL) // Parse asynchronously, not to block the UI. parser.parseAsync { [weak self] (result) in guard let self = self else { return } switch result { case .success(let feed): // Grab the parsed feed directly as an optional rss, atom or json feed object self.feed = feed.rssFeed // Or alternatively... // // switch feed { // case .rss(let feed): break // case .atom(let feed): break // case .json(let feed): break // } // Then back to the Main thread to update the UI. DispatchQueue.main.async { self.feedItemsTableView.reloadData() } case .failure(let error): print(error) } } } // MARK: - Text View Helper func updateTextView() { let selectedRow = self.feedItemsTableView.selectedRow if selectedRow > -1 { let item = self.feed!.items![selectedRow] self.textView.string = item.description! } } } // MARK: - Table View Delegate extension ViewController: NSTableViewDelegate { func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? { guard let cell = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "Cell"), owner: nil) as? NSTableCellView else { return nil } switch tableView { case self.feedTableView: switch row { case 0: cell.textField?.stringValue = self.feed?.title ?? "[no title]" case 1: cell.textField?.stringValue = self.feed?.link ?? "[no link]" case 2: cell.textField?.stringValue = self.feed?.description ?? "[no description]" default: fatalError() } case self.feedItemsTableView: cell.textField?.stringValue = self.feed!.items![row].title ?? "[no title]" default: fatalError() } return cell } func tableViewSelectionDidChange(_ notification: Notification) { self.updateTextView() } } // MARK: - Table View Data Source extension ViewController: NSTableViewDataSource { func numberOfRows(in tableView: NSTableView) -> Int { switch tableView { case self.feedTableView: return 3 case self.feedItemsTableView: return self.feed?.items?.count ?? 0 default: fatalError() } } }
bcaedf3d601f3fb7352f6d79852b4d82
32.083333
147
0.602931
false
false
false
false
ygweric/swift-extension
refs/heads/master
UIView+Extension.swift
apache-2.0
1
// // UIView+Extension.swift // ZBCool // // Created by ericyang on 11/23/15. // Copyright © 2015 i-chou. All rights reserved. // import UIKit extension UIView{ var width: CGFloat { get{ return self.frame.size.width } set{ self.frame.size.width = newValue } } var height: CGFloat { get{ return self.frame.size.height } set{ self.frame.size.height = newValue } } var size: CGSize { get{ return self.frame.size } set{ self.frame.size = newValue } } var origin: CGPoint { get{ return self.frame.origin } set{ self.frame.origin = newValue } } var x: CGFloat { get{ return self.frame.origin.x } set{ self.frame.origin = CGPointMake(newValue, self.frame.origin.y) } } var y: CGFloat { get{ return self.frame.origin.y } set{ self.frame.origin = CGPointMake(self.frame.origin.x, newValue) } } var centerX: CGFloat { get{ return self.center.x } set{ self.center = CGPointMake(newValue, self.center.y) } } var centerY: CGFloat { get{ return self.center.y } set{ self.center = CGPointMake(self.center.x, newValue) } } var minX: CGFloat { get{ return self.frame.origin.x } set{ self.frame.origin.x = newValue } } var maxX: CGFloat { get{ return self.frame.origin.x + self.frame.size.width } set{ self.frame.origin.x = newValue - self.frame.size.width } } var minY: CGFloat { get{ return self.frame.origin.y } set{ self.frame.origin.y = newValue } } var maxY: CGFloat { get{ return self.frame.origin.y + self.frame.size.height } set{ self.frame.origin.y = newValue - self.frame.size.height } } convenience init( frame_:CGRect = CGRectZero, backgroundColor:UIColor = UIColor.clearColor() ){ self.init(frame:frame_) self.backgroundColor=backgroundColor } }
9cc3d42fa904740490d2c54d08964200
19.926829
74
0.460373
false
false
false
false
mercadopago/sdk-ios
refs/heads/master
MercadoPagoSDK/MercadoPagoSDK/CustomerCardsViewController.swift
mit
1
// // CustomerCardsViewController.swift // MercadoPagoSDK // // Created by Matias Gualino on 31/12/14. // Copyright (c) 2014 com.mercadopago. All rights reserved. // import Foundation import UIKit public class CustomerCardsViewController : UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak private var tableView : UITableView! var loadingView : UILoadingView! var items : [PaymentMethodRow]! var cards : [Card]? var bundle : NSBundle? = MercadoPago.getBundle() var callback : ((selectedCard: Card?) -> Void)? public init(cards: [Card]?, callback: (selectedCard: Card?) -> Void) { super.init(nibName: "CustomerCardsViewController", bundle: bundle) self.cards = cards self.callback = callback } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func viewDidAppear(animated: Bool) { self.tableView.reloadData() } override public func viewDidLoad() { super.viewDidLoad() self.title = "Medios de pago".localized self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Atrás".localized, style: UIBarButtonItemStyle.Plain, target: nil, action: nil) self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add, target: self, action: "newCard") self.loadingView = UILoadingView(frame: MercadoPago.screenBoundsFixedToPortraitOrientation(), text: "Cargando...".localized) self.view.addSubview(self.loadingView) let paymentMethodNib = UINib(nibName: "PaymentMethodTableViewCell", bundle: self.bundle) self.tableView.registerNib(paymentMethodNib, forCellReuseIdentifier: "paymentMethodCell") self.tableView.delegate = self self.tableView.dataSource = self loadCards() } public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items == nil ? 0 : items.count } public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let pmcell : PaymentMethodTableViewCell = self.tableView.dequeueReusableCellWithIdentifier("paymentMethodCell") as! PaymentMethodTableViewCell let paymentRow : PaymentMethodRow = items[indexPath.row] pmcell.setLabel(paymentRow.label!) pmcell.setImageWithName(paymentRow.icon!) return pmcell } public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 44 } public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { callback!(selectedCard: self.cards![indexPath.row]) } public func loadCards() { self.items = [PaymentMethodRow]() for (card) in cards! { let paymentMethodRow = PaymentMethodRow() paymentMethodRow.card = card paymentMethodRow.label = card.paymentMethod!.name + " " + "terminada en".localized + " " + card.lastFourDigits! paymentMethodRow.icon = "icoTc_" + card.paymentMethod!._id self.items.append(paymentMethodRow) } self.tableView.reloadData() self.loadingView.removeFromSuperview() } public func newCard() { callback!(selectedCard: nil) } }
193393867546852ac031c8598a28435d
36.244681
150
0.676
false
false
false
false
lemonandlime/Strax
refs/heads/master
Strax/SLDataProvider.swift
gpl-2.0
1
// // SLDataProvider.swift // Strax // // Created by Karl Söderberg on 2015-05-30. // Copyright (c) 2015 lemonandlime. All rights reserved. // import UIKit import SwiftyJSON import Alamofire private let _sharedInstance = SLDataProvider() private let baseUrl = "http://api.sl.se/api2/" private let key = "35ea4763c2cc4c47b9aaef634b728943" private let nameKey = "814ca053c1774eedaf6cfd61e2c7e886" class SLDataProvider: NSObject { class var sharedInstance : SLDataProvider { return _sharedInstance } func getTrip(from:String, to: String, onCompletion: (Result<Array<Trip>, NSError>) -> Void) { let parameters = ["key":key, "originId":from, "destId":to] Alamofire.request( .GET, NSURL(string: baseUrl+"TravelplannerV2/trip.JSON")!, parameters: parameters, encoding: .URL, headers: nil) .responseData { (response) -> Void in switch response.result { case .Success(let object): let json = JSON(data: object) var trips = Array<Trip>() json["TripList"]["Trip"].forEach({ (_, trip: JSON) -> (Void) in trips.append(Trip(info: trip)) }) onCompletion(Result.Success(trips)) break case.Failure(let error): onCompletion(Result.Failure(error)) break } } } func getLocation(name:String, onCompletion: (Result<AnyObject, NSError>) ->Void){ let parameters = ["key":nameKey, "searchstring":name] Alamofire.request( .GET, NSURL(string: baseUrl+"typeahead.JSON")!, parameters: parameters, encoding: .URL, headers: nil) .responseData { (response) -> Void in switch response.result{ case .Success(let object): let json = JSON(data: object) if json["ResponseData"].array?.count > 0{ onCompletion(Result.Success(json["ResponseData"].arrayObject![0])) }else{ onCompletion(Result.Failure( NSError(domain: "SLData", code: 101, userInfo: nil))) } case .Failure(let error): onCompletion(Result.Failure(error)) } } } }
25edcd8087b77d2b391f9b89626f00ba
30.1
102
0.532556
false
false
false
false
mobilabsolutions/jenkins-ios
refs/heads/master
JenkinsiOS/Model/JenkinsAPI/Job/Job.swift
mit
1
// // Job.swift // JenkinsiOS // // Created by Robert on 23.09.16. // Copyright © 2016 MobiLab Solutions. All rights reserved. // import Foundation class Job: Favoratible { // MARK: - Minimal Version /// The job's name var name: String /// The job's url var url: URL /// The job's color indicating its current status var color: JenkinsColor? // MARK: - Full version /// The job's description var description: String? /// Whether or not the Job is currently buildable var buildable: Bool? /// All recently performed builds on the Job var builds: [Build] = [] /// The results of health reports in the job var healthReport: [HealthReportResult] = [] /// Whether or not the Job is currently in a queue var inQueue: Bool? /// Whether or not dependencies are kept in the Job var keepDependencies: Bool? /// The first performed build in the job var firstBuild: Build? /// The last build var lastBuild: Build? /// The last completed build var lastCompletedBuild: Build? /// The last failed build var lastFailedBuild: Build? /// The last stable build var lastStableBuild: Build? /// The last successful build var lastSuccessfulBuild: Build? /// The last unstable build var lastUnstableBuild: Build? /// The last unsuccessful build var lastUnsuccessfulBuild: Build? /// An array of special builds: First, last, last completed, etc. var specialBuilds: [(String, Build?)] = [] /// The number of the next to be performed build var nextBuildNumber: Int? /// Is the job information based on "full version" JSON? var isFullVersion = false /// The job's build parameters, if any var parameters: [Parameter] = [] /// Whether or not the job was previously built var wasBuilt: Bool { return color != .notBuilt } /// Optionally initialize a Job /// /// - parameter json: The json from which to initialize the job /// - parameter minimalVersion: Whether or not the json represents a minimal version of the job /// /// - returns: The initialized Job object or nil, if initialization failed init?(json: [String: AnyObject], minimalVersion: Bool = false, isBuildMinimalVersion: Bool = true) { guard let nameUrlString = json[Constants.JSON.name] as? String, let name = nameUrlString.removingPercentEncoding, let urlString = json[Constants.JSON.url] as? String else { return nil } guard let url = URL(string: urlString) else { return nil } if let stringColor = json["color"] as? String { color = JenkinsColor(rawValue: stringColor) } else { color = JenkinsColor.folder } self.url = url self.name = name healthReport = (json["healthReport"] as? [[String: AnyObject]])? .map { HealthReportResult(json: $0) }.compactMap { $0 } ?? [] lastBuild = json["lastBuild"] as? [String: AnyObject] == nil ? nil : Build(json: json["lastBuild"] as! [String: AnyObject], minimalVersion: isBuildMinimalVersion) // The minimal version only contains these select fields if !minimalVersion { addAdditionalFields(from: json, isBuildMinimalVersion: isBuildMinimalVersion) } } /// Add values for fields in the full job category /// /// - parameter json: The JSON parsed data from which to get the values for the additional fields func addAdditionalFields(from json: [String: AnyObject], isBuildMinimalVersion: Bool) { if let stringColor = json["color"] as? String { color = JenkinsColor(rawValue: stringColor) } description = json["description"] as? String buildable = json["buildable"] as? Bool inQueue = json["inQueue"] as? Bool keepDependencies = json["keepDependencies"] as? Bool builds = (json["builds"] as? [[String: AnyObject]])?.map { Build(json: $0, minimalVersion: isBuildMinimalVersion) }.filter { $0 != nil }.map { $0! } ?? [] // Get the interesting builds from the json data and, if they can be converted to a dictionary, try to initialize a Build from them firstBuild = json["firstBuild"] as? [String: AnyObject] == nil ? nil : Build(json: json["firstBuild"] as! [String: AnyObject], minimalVersion: isBuildMinimalVersion) lastBuild = json["lastBuild"] as? [String: AnyObject] == nil ? nil : Build(json: json["lastBuild"] as! [String: AnyObject], minimalVersion: isBuildMinimalVersion) lastCompletedBuild = json["lastCompletedBuild"] as? [String: AnyObject] == nil ? nil : Build(json: json["lastCompletedBuild"] as! [String: AnyObject], minimalVersion: isBuildMinimalVersion) lastFailedBuild = json["lastFailedBuild"] as? [String: AnyObject] == nil ? nil : Build(json: json["lastFailedBuild"] as! [String: AnyObject], minimalVersion: isBuildMinimalVersion) lastStableBuild = json["lastStableBuild"] as? [String: AnyObject] == nil ? nil : Build(json: json["lastStableBuild"] as! [String: AnyObject], minimalVersion: isBuildMinimalVersion) lastSuccessfulBuild = json["lastSuccessfulBuild"] as? [String: AnyObject] == nil ? nil : Build(json: json["lastSuccessfulBuild"] as! [String: AnyObject], minimalVersion: isBuildMinimalVersion) lastUnstableBuild = json["lastUnstableBuild"] as? [String: AnyObject] == nil ? nil : Build(json: json["lastUnstableBuild"] as! [String: AnyObject], minimalVersion: isBuildMinimalVersion) lastUnsuccessfulBuild = json["lastUnsuccessfulBuild"] as? [String: AnyObject] == nil ? nil : Build(json: json["lastUnsuccessfulBuild"] as! [String: AnyObject], minimalVersion: isBuildMinimalVersion) nextBuildNumber = json["nextBuildNumber"] as? Int specialBuilds = [ ("Last Build", lastBuild), ("Last Successful Build", lastSuccessfulBuild), ("Last Failed Build", lastFailedBuild), ("Last Unsuccessful Build", lastUnsuccessfulBuild), ("Last Completed Build", lastCompletedBuild), ("First Build", firstBuild), ] // Parse all the parameters parameters = [] // For some reason there are multiple places in which the parameters may be defined. We // will a let possibleParameterDefinitionPlaces = [Constants.JSON.property, Constants.JSON.actions] for possibleParameterDefinitionPlace in possibleParameterDefinitionPlaces { if let properties = json[possibleParameterDefinitionPlace] as? [[String: Any]], let parametersJson = properties.first(where: { $0[Constants.JSON.parameterDefinitions] != nil })?[Constants.JSON.parameterDefinitions] as? [[String: Any]] { for parameterJson in parametersJson { guard let parameter = Parameter(json: parameterJson) else { continue } parameters.append(parameter) } break } } isFullVersion = true } }
b7db40d075db09d76c868c03c1d37d36
41.714286
206
0.647297
false
false
false
false
iRoxx/WordPress-iOS
refs/heads/develop
WordPress/Classes/ViewRelated/Notifications/RichTextView/RichTextView.swift
gpl-2.0
1
import Foundation @objc public protocol RichTextViewDataSource { optional func textView(textView: UITextView, viewForTextAttachment attachment: NSTextAttachment) -> UIView? } @objc public protocol RichTextViewDelegate : UITextViewDelegate { optional func textView(textView: UITextView, didPressLink link: NSURL) } @objc public class RichTextView : UIView, UITextViewDelegate { public var dataSource: RichTextViewDataSource? public var delegate: RichTextViewDelegate? // MARK: - Initializers public override init() { super.init() setupSubviews() } public override init(frame: CGRect) { super.init(frame: frame) setupSubviews() } public required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setupSubviews() } // MARK: - Properties public var contentInset: UIEdgeInsets = UIEdgeInsetsZero { didSet { textView?.contentInset = contentInset } } public var textContainerInset: UIEdgeInsets = UIEdgeInsetsZero { didSet { textView?.textContainerInset = textContainerInset } } public var attributedText: NSAttributedString! { didSet { assert(textView != nil) textView.attributedText = attributedText ?? NSAttributedString() renderAttachments() } } public var editable: Bool = false { didSet { textView?.editable = editable } } public var selectable: Bool = true { didSet { textView?.selectable = selectable } } public var dataDetectorTypes: UIDataDetectorTypes = .None { didSet { textView?.dataDetectorTypes = dataDetectorTypes } } public override var backgroundColor: UIColor? { didSet { textView?.backgroundColor = backgroundColor } } public var linkTextAttributes: [NSObject : AnyObject]! { didSet { textView?.linkTextAttributes = linkTextAttributes } } // MARK: - TextKit Getters public var layoutManager: NSLayoutManager { get { return textView.layoutManager } } public var textStorage: NSTextStorage { get { return textView.textStorage } } public var textContainer: NSTextContainer { get { return textView.textContainer } } // MARK: - Autolayout Helpers public var preferredMaxLayoutWidth: CGFloat = 0 { didSet { invalidateIntrinsicContentSize() } } public override func intrinsicContentSize() -> CGSize { // Fix: Let's add 1pt extra size. There are few scenarios in which text gets clipped by 1 point let bottomPadding = CGFloat(1) let maxWidth = (preferredMaxLayoutWidth != 0) ? preferredMaxLayoutWidth : frame.width let maxSize = CGSize(width: maxWidth, height: CGFloat.max) let requiredSize = textView!.sizeThatFits(maxSize) let roundedSize = CGSize(width: ceil(requiredSize.width), height: ceil(requiredSize.height) + bottomPadding) return roundedSize } // MARK: - Private Methods private func setupSubviews() { gesturesRecognizer = UITapGestureRecognizer() gesturesRecognizer.addTarget(self, action: "handleTextViewTap:") textView = UITextView(frame: bounds) textView.backgroundColor = backgroundColor textView.contentInset = UIEdgeInsetsZero textView.textContainerInset = UIEdgeInsetsZero textView.textContainer.lineFragmentPadding = 0 textView.layoutManager.allowsNonContiguousLayout = false textView.editable = editable textView.dataDetectorTypes = dataDetectorTypes textView.delegate = self textView.gestureRecognizers = [gesturesRecognizer] addSubview(textView) // Setup Layout textView.setTranslatesAutoresizingMaskIntoConstraints(false) pinSubviewToAllEdges(textView) } private func renderAttachments() { // Nuke old attachments attachmentViews.map { $0.removeFromSuperview() } attachmentViews.removeAll(keepCapacity: false) // Proceed only if needed if attributedText == nil { return } // Load new attachments attributedText.enumerateAttachments { (attachment: NSTextAttachment, range: NSRange) -> () in let attachmentView = self.dataSource?.textView?(self.textView, viewForTextAttachment: attachment) if attachmentView == nil { return } let unwrappedView = attachmentView! unwrappedView.frame.origin = self.textView.frameForTextInRange(range).integerRect.origin self.textView.addSubview(unwrappedView) self.attachmentViews.append(unwrappedView) } } // MARK: - UITapGestureRecognizer Helpers public func handleTextViewTap(recognizer: UITapGestureRecognizer) { // NOTE: Why do we need this? // Because this mechanism allows us to disable DataDetectors, and yet, detect taps on links. // let textStorage = textView.textStorage let layoutManager = textView.layoutManager let textContainer = textView.textContainer let locationInTextView = recognizer.locationInView(textView) let characterIndex = layoutManager.characterIndexForPoint(locationInTextView, inTextContainer: textContainer, fractionOfDistanceBetweenInsertionPoints: nil) if characterIndex >= textStorage.length { return } // Load the NSURL instance, if any let rawURL = textStorage.attribute(NSLinkAttributeName, atIndex: characterIndex, effectiveRange: nil) as? NSURL if let unwrappedURL = rawURL { delegate?.textView?(textView, didPressLink: unwrappedURL) } } // MARK: - UITextViewDelegate Wrapped Methods public func textViewShouldBeginEditing(textView: UITextView) -> Bool { return delegate?.textViewShouldBeginEditing?(textView) ?? true } public func textViewShouldEndEditing(textView: UITextView) -> Bool { return delegate?.textViewShouldEndEditing?(textView) ?? true } public func textViewDidBeginEditing(textView: UITextView) { delegate?.textViewDidBeginEditing?(textView) } public func textViewDidEndEditing(textView: UITextView) { delegate?.textViewDidEndEditing?(textView) } public func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { return delegate?.textView?(textView, shouldChangeTextInRange: range, replacementText: text) ?? true } public func textViewDidChange(textView: UITextView) { delegate?.textViewDidChange?(textView) } public func textViewDidChangeSelection(textView: UITextView) { delegate?.textViewDidChangeSelection?(textView) } public func textView(textView: UITextView, shouldInteractWithURL URL: NSURL, inRange characterRange: NSRange) -> Bool { return delegate?.textView?(textView, shouldInteractWithURL: URL, inRange: characterRange) ?? true } public func textView(textView: UITextView, shouldInteractWithTextAttachment textAttachment: NSTextAttachment, inRange characterRange: NSRange) -> Bool { return delegate?.textView?(textView, shouldInteractWithTextAttachment: textAttachment, inRange: characterRange) ?? true } // MARK: - Private Properites private var textView: UITextView! private var gesturesRecognizer: UITapGestureRecognizer! private var attachmentViews: [UIView] = [] }
eca5d4946c2424c91cc41b6d5e1d8980
33.510121
156
0.612389
false
false
false
false
SwiftKit/Cuckoo
refs/heads/master
Generator/Source/CuckooGeneratorFramework/Tokens/ContainerToken.swift
mit
1
// // ContainerToken.swift // CuckooGenerator // // Created by Filip Dolnik on 30.05.16. // Copyright © 2016 Brightify. All rights reserved. // public protocol ContainerToken: Token, HasAccessibility { var name: String { get } var range: CountableRange<Int> { get } var nameRange: CountableRange<Int> { get } var bodyRange: CountableRange<Int> { get } var initializers: [Initializer] { get } var children: [Token] { get } var implementation: Bool { get } var inheritedTypes: [InheritanceDeclaration] { get } var attributes: [Attribute] { get } var genericParameters: [GenericParameter] { get } } extension ContainerToken { public func serialize() -> [String : Any] { func withAdjustedAccessibility(token: Token & HasAccessibility) -> Token & HasAccessibility { // We only want to adjust tokens that are accessible and lower than the enclosing type guard token.accessibility.isAccessible && token.accessibility < accessibility else { return token } var mutableToken = token mutableToken.accessibility = accessibility return mutableToken } let accessibilityAdjustedChildren = children.map { child -> Token in guard let childWithAccessibility = child as? HasAccessibility & Token else { return child } return withAdjustedAccessibility(token: childWithAccessibility) } let properties = accessibilityAdjustedChildren.compactMap { $0 as? InstanceVariable } .filter { $0.accessibility.isAccessible } .map { $0.serializeWithType() } let methods = accessibilityAdjustedChildren.compactMap { $0 as? Method } .filter { $0.accessibility.isAccessible && !$0.isInit && !$0.isDeinit } .map { $0.serializeWithType() } let initializers = accessibilityAdjustedChildren.compactMap { $0 as? Method } .filter { $0.accessibility.isAccessible && $0.isInit && !$0.isDeinit } .map { $0.serializeWithType() } let genericParametersString = genericParameters.map { $0.description }.joined(separator: ", ") let genericArgumentsString = genericParameters.map { $0.name }.joined(separator: ", ") let genericProtocolIdentity = genericParameters.map { "\(Templates.staticGenericParameter).\($0.name) == \($0.name)" }.joined(separator: ", ") let isGeneric = !genericParameters.isEmpty return [ "name": name, "accessibility": accessibility.sourceName, "isAccessible": accessibility.isAccessible, "children": accessibilityAdjustedChildren.map { $0.serializeWithType() }, "properties": properties, "methods": methods, "initializers": implementation ? [] : initializers, "isImplementation": implementation, "mockName": "Mock\(name)", "inheritedTypes": inheritedTypes, "attributes": attributes.filter { $0.isSupported }, "isGeneric": isGeneric, "genericParameters": isGeneric ? "<\(genericParametersString)>" : "", "genericArguments": isGeneric ? "<\(genericArgumentsString)>" : "", "genericProtocolIdentity": genericProtocolIdentity, ] } }
88490f6297cea4e35393513734656344
44.861111
150
0.642944
false
false
false
false
aaronraimist/firefox-ios
refs/heads/master
Storage/SuggestedSites.swift
mpl-2.0
3
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import XCGLogger import UIKit import Shared private let log = XCGLogger.defaultInstance() public class SuggestedSite: Site { public let wordmark: Favicon public let backgroundColor: UIColor override public var tileURL: NSURL { return NSURL(string: url) ?? NSURL(string: "about:blank")! } let trackingId: Int init(data: SuggestedSiteData) { self.backgroundColor = UIColor(colorString: data.bgColor) self.trackingId = data.trackingId self.wordmark = Favicon(url: data.imageUrl, date: NSDate(), type: .Icon) super.init(url: data.url, title: data.title, bookmarked: nil) self.icon = Favicon(url: data.faviconUrl, date: NSDate(), type: .Icon) } } public let SuggestedSites: SuggestedSitesCursor = SuggestedSitesCursor() public class SuggestedSitesCursor: ArrayCursor<SuggestedSite> { private init() { let locale = NSLocale.currentLocale() let sites = DefaultSuggestedSites.sites[locale.localeIdentifier] ?? DefaultSuggestedSites.sites["default"]! as Array<SuggestedSiteData> let tiles = sites.map({data in SuggestedSite(data: data)}) super.init(data: tiles, status: .Success, statusMessage: "Loaded") } } public struct SuggestedSiteData { var url: String var bgColor: String var imageUrl: String var faviconUrl: String var trackingId: Int var title: String }
6e44d9ee94bf523b9e013be14604d25a
32.895833
87
0.692071
false
false
false
false
tunespeak/AlamoRecord
refs/heads/master
Example/AlamoRecord/PostsView.swift
mit
1
// // PostsView.swift // AlamoRecord // // Created by Dalton Hinterscher on 7/6/17. // Copyright © 2017 CocoaPods. All rights reserved. // import SnapKit import UIKit protocol PostsViewDelegate: class { func numberOfPosts() -> Int func post(at index: Int) -> Post func commentsButtonPressed(at index: Int) func destroyButtonPressed(at index: Int) } class PostsView: UIView { fileprivate weak var delegate: PostsViewDelegate? private(set) var tableView: UITableView! init(delegate: PostsViewDelegate) { super.init(frame: .zero) self.backgroundColor = .white self.delegate = delegate tableView = UITableView(frame: .zero, style: .plain) tableView.backgroundColor = .darkWhite tableView.separatorStyle = .none tableView.rowHeight = UITableView.automaticDimension tableView.estimatedRowHeight = 50.0 tableView.dataSource = self tableView.delegate = self tableView.contentInset = UIEdgeInsets.init(top: 0, left: 0, bottom: 10, right: 0) addSubview(tableView) tableView.snp.makeConstraints { (make) in make.edges.equalToSuperview() } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension PostsView: UITableViewDataSource { internal func numberOfSections(in tableView: UITableView) -> Int { return 1 } internal func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return delegate!.numberOfPosts() } internal func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { var cell: PostCell? = tableView.dequeueReusableCell(withIdentifier: PostCell.reuseIdentifier) as? PostCell if cell == nil { cell = PostCell() cell?.delegate = self } cell?.bind(post: delegate!.post(at: indexPath.row)) return cell! } } extension PostsView: UITableViewDelegate { internal func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: false) } } extension PostsView: PostCellDelegate { internal func commentsButtonPressed(at index: Int) { delegate?.commentsButtonPressed(at: index) } internal func destroyButtonPressed(at index: Int) { delegate?.destroyButtonPressed(at: index) } }
ba62711e91b241d88173bb052b2f6fe6
27.544444
114
0.655119
false
false
false
false
simonwhitehouse/SWHGameOfLife
refs/heads/master
SWHGameOfLife/SWHGameOfLife/LivingView.swift
mit
1
// // LivingView.swift // SWHGameOfLife // // Created by Simon J Whitehouse on 01/10/2015. // Copyright © 2015 co.swhitehouse. All rights reserved. // import Foundation import UIKit enum LivingViewState { case Alive, Dead /// creates a random cell state either alive or dead static func randomCellState() -> LivingViewState { let randomNumber = arc4random_uniform(2) == 1 if randomNumber { return .Alive } else { return .Dead } } } /// Living View - represents a cell that is alive (white) or dead (black) class LivingView: UIView { /// the curent living state of the view var currentLivingViewState: LivingViewState = .Dead { didSet { backgroundColor = currentLivingViewState == .Alive ? UIColor.whiteColor() : UIColor.clearColor() } } /// tap gesture for recognising taps lazy var tapGesture: UITapGestureRecognizer = { var tempTap = UITapGestureRecognizer(target: self, action: "tapped:") return tempTap }() func tapped(tapGesture: UITapGestureRecognizer) { currentLivingViewState = currentLivingViewState == .Dead ? .Alive : .Dead } func configure(startState: LivingViewState) { addGestureRecognizer(tapGesture) currentLivingViewState = startState } }
e4e9f2bb883b7a291965ebfd32f98a65
25.921569
108
0.640671
false
false
false
false
jpchmura/JPCDataSourceController
refs/heads/master
Source/BackgroundView.swift
mit
1
// // BackgroundView.swift // JPCDataSourceController // // Created by Jon Chmura on 3/31/15. // Copyright (c) 2015 Jon Chmura. All rights reserved. // // // Source: https://github.com/jpchmura/JPCDataSourceController // // License: MIT ( http://opensource.org/licenses/MIT ) // import UIKit public extension BackgroundView { /// The errorView cast as a StandardErrorView. public var standardErrorView: StandardErrorView? { get { return self.errorView as? StandardErrorView } } } /** * A background view for TableView or CollectionView containing views for Pull To Refresh, Loading / Error Status, and Paging */ public class BackgroundView: UIView { public enum Views { case PullToRefresh, Loading, Error, Paging } public var visibleViews: Set<Views> = Set([]) { didSet { self.pullToRefreshView?.hidden = !visibleViews.contains(.PullToRefresh) self.loadingView?.hidden = !visibleViews.contains(.Loading) self.errorView?.hidden = !visibleViews.contains(.Error) self.pagingView?.hidden = !visibleViews.contains(.Paging) } } /// The height of the pull to refresh view. Equals the distance in points beyond the top of the content the table must to scrolled to activate pull to refresh. public var pullToRefreshDistance: CGFloat = 120 /// The pull to refresh view or nil to not use one. public var pullToRefreshView: PullToRefreshView? { didSet { oldValue?.removeFromSuperview() if let pullToRefreshView = pullToRefreshView { self.addSubview(pullToRefreshView) } refreshConstraints() } } /// The loading status view or nil to not use one. public var loadingView: LoadingView? { didSet { oldValue?.removeFromSuperview() if let loadingView = loadingView { self.addSubview(loadingView) } refreshConstraints() } } /// The error view or nil to not use one. public var errorView: UIView? { didSet { oldValue?.removeFromSuperview() if let errorView = errorView { self.addSubview(errorView) } refreshConstraints() } } /// The paging status view or nil to not use one. public var pagingView: PagingView? { didSet { oldValue?.removeFromSuperview() if let pagingView = pagingView { self.addSubview(pagingView) } refreshConstraints() } } private var _constraints = [NSLayoutConstraint]() public func refreshConstraints() { // Had issues using "updateConstraints" API. Might be due to layout of table / collection view background view. removeConstraints(_constraints) _constraints.removeAll() func layoutToEdges(view: UIView) -> [NSLayoutConstraint] { let views = ["view" : view] return NSLayoutConstraint.constraintsWithVisualFormat("H:|[view]|", options: [], metrics: nil, views: views) + NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: [], metrics: nil, views: views) } if let pullToRefresh = pullToRefreshView { pullToRefresh.translatesAutoresizingMaskIntoConstraints = false _constraints += layoutToEdges(pullToRefresh) } if let loadingView = loadingView { loadingView.translatesAutoresizingMaskIntoConstraints = false _constraints += layoutToEdges(loadingView) } if let errorView = errorView { errorView.translatesAutoresizingMaskIntoConstraints = false _constraints += layoutToEdges(errorView) } if let pagingView = pagingView { pagingView.translatesAutoresizingMaskIntoConstraints = false _constraints += layoutToEdges(pagingView) } addConstraints(_constraints) } private func commonInit() { self.loadingView = StandardLoadingView() self.errorView = StandardErrorView() } public convenience init() { self.init(frame: CGRectZero) } public override init(frame: CGRect) { super.init(frame: frame) self.commonInit() } public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.commonInit() } }
afbced00293584edfaeda0ad73ed5208
28.425
163
0.597069
false
false
false
false
CodaFi/swift
refs/heads/master
test/decl/typealias/protocol.swift
apache-2.0
8
// RUN: %target-typecheck-verify-swift // Tests for typealias inside protocols protocol Bad { associatedtype X<T> // expected-error {{associated types must not have a generic parameter list}} typealias Y<T> // expected-error {{expected '=' in type alias declaration}} } protocol Col { associatedtype Elem typealias E = Elem? var elem: Elem { get } } protocol CB { associatedtype C : Col // Self at top level typealias S = Self func cloneDefinitely() -> S // Self in bound generic position typealias OS = Self? func cloneMaybe() -> OS // Associated type of archetype typealias E = C.Elem func setIt(_ element: E) // Typealias of archetype typealias EE = C.E func setItSometimes(_ element: EE) // Associated type in bound generic position typealias OE = C.Elem? func setItMaybe(_ element: OE) // Complex type expression typealias FE = (C) -> (C.Elem) -> Self func teleport(_ fn: FE) } // Generic signature requirement involving protocol typealias func go1<T : CB, U : Col>(_ col: U, builder: T) where U.Elem == T.E { // OK builder.setIt(col.elem) } func go2<T : CB, U : Col>(_ col: U, builder: T) where U.Elem == T.C.Elem { // OK builder.setIt(col.elem) } // Test for same type requirement with typealias == concrete func go3<T : CB>(_ builder: T) where T.E == Int { builder.setIt(1) } // Test for conformance to protocol with associatedtype and another with // typealias with same name protocol MyIterator { associatedtype Elem func next() -> Elem? } protocol MySeq { associatedtype I : MyIterator typealias Elem = Self.I.Elem func makeIterator() -> I func getIndex(_ i: Int) -> Elem func first() -> Elem } extension MySeq where Self : MyIterator { func makeIterator() -> Self { return self } } func plusOne<S: MySeq>(_ s: S, i: Int) -> Int where S.Elem == Int { return s.getIndex(i) + 1 } struct OneIntSeq: MySeq, MyIterator { let e : Float func next() -> Float? { return e } func getIndex(_ i: Int) -> Float { return e } } protocol MyIntIterator { typealias Elem = Int } struct MyIntSeq : MyIterator, MyIntIterator { func next() -> Elem? { return 0 } } protocol MyIntIterator2 {} extension MyIntIterator2 { typealias Elem = Int } struct MyIntSeq2 : MyIterator, MyIntIterator2 { func next() -> Elem? { return 0 } } // test for conformance correctness using typealias in extension extension MySeq { func first() -> Elem { return getIndex(0) } } // Typealiases whose underlying type is a structural type written in terms of // associated types protocol P1 { associatedtype A typealias F = (A) -> () } protocol P2 { associatedtype B } func go3<T : P1, U : P2>(_ x: T) -> U where T.F == U.B { } // Specific diagnosis for things that look like Swift 2.x typealiases protocol P3 { typealias T // expected-error {{type alias is missing an assigned type; use 'associatedtype' to define an associated type requirement}} typealias U : P2 // expected-error {{type alias is missing an assigned type; use 'associatedtype' to define an associated type requirement}} } // Test for not crashing on recursive aliases protocol Circular { typealias Y = Self.Y // expected-error {{type alias 'Y' references itself}} expected-note {{while resolving type 'Self.Y'}} typealias Y2 = Y2 // expected-error {{type alias 'Y2' references itself}} expected-note {{while resolving type 'Y2'}} typealias Y3 = Y4 // expected-error {{type alias 'Y3' references itself}} expected-note {{while resolving type 'Y4'}} typealias Y4 = Y3 // expected-note {{through reference here}} expected-note {{while resolving type 'Y3'}} } // Qualified and unqualified references to protocol typealiases from concrete type protocol P5 { associatedtype A typealias X = Self typealias T1 = Int typealias T2 = A var a: T2 { get } } protocol P6 { typealias A = Int typealias B = Self } struct T5 : P5 { // This is OK -- the typealias is fully concrete var a: P5.T1 // OK // Invalid -- cannot represent associated type of existential var v2: P5.T2 // expected-error {{type alias 'T2' can only be used with a concrete type or generic parameter base}} var v3: P5.X // expected-error {{type alias 'X' can only be used with a concrete type or generic parameter base}} // Unqualified reference to typealias from a protocol conformance var v4: T1 // OK var v5: T2 // OK // Qualified reference var v6: T5.T1 // OK var v7: T5.T2 // OK var v8 = P6.A.self var v9 = P6.B.self // expected-error {{type alias 'B' can only be used with a concrete type or generic parameter base}} } // Unqualified lookup finds typealiases in protocol extensions protocol P7 { associatedtype A typealias Z = A } extension P7 { typealias Y = A } struct S7 : P7 { typealias A = Int func inTypeContext(y: Y) { } func inExpressionContext() { _ = Y.self _ = Z.self _ = T5.T1.self _ = T5.T2.self } } protocol P8 { associatedtype B @available(*, unavailable, renamed: "B") typealias A = B // expected-note{{'A' has been explicitly marked unavailable here}} } func testP8<T: P8>(_: T) where T.A == Int { } // expected-error{{'A' has been renamed to 'B'}}{{34-35=B}} // Associated type resolution via lookup should find typealiases in protocol extensions protocol Edible { associatedtype Snack } protocol CandyWrapper { associatedtype Wrapped } extension CandyWrapper where Wrapped : Edible { typealias Snack = Wrapped.Snack } struct Candy {} struct CandyBar : CandyWrapper { typealias Wrapped = CandyEdible } struct CandyEdible : Edible { typealias Snack = Candy } // Edible.Snack is witnessed by 'typealias Snack' inside the // constrained extension of CandyWrapper above extension CandyBar : Edible {} protocol P9 { typealias A = Int } func testT9a<T: P9, U>(_: T, _: U) where T.A == U { } // expected-error {{same-type requirement makes generic parameter 'U' non-generic}} func testT9b<T: P9>(_: T) where T.A == Float { } // expected-error{{generic signature requires types 'T.A' (aka 'Int') and 'Float' to be the same}} struct X<T> { } protocol P10 { associatedtype A typealias T = Int @available(*, deprecated, message: "just use Int, silly") typealias V = Int } extension P10 { typealias U = Float } extension P10 where T == Int { } // expected-warning{{neither type in same-type constraint ('Self.T' (aka 'Int') or 'Int') refers to a generic parameter or associated type}} extension P10 where A == X<T> { } extension P10 where A == X<U> { } extension P10 where A == X<Self.U> { } extension P10 where V == Int { } // expected-warning 2{{'V' is deprecated: just use Int, silly}} // expected-warning@-1{{neither type in same-type constraint ('Self.V' (aka 'Int') or 'Int') refers to a generic parameter or associated type}} // rdar://problem/36003312 protocol P11 { typealias A = Y11 } struct X11<T: P11> { } struct Y11: P11 { } extension P11 { func foo(_: X11<Self.A>) { } } // Ordering issue struct SomeConformingType : UnboundGenericAliasProto { func f(_: G<Int>) {} } protocol UnboundGenericAliasProto { typealias G = X } // If pre-checking cannot resolve a member type due to ambiguity, // we go down the usual member access path. Make sure its correct // for protocol typealiases. protocol Amb1 { typealias T = Int } protocol Amb2 { typealias T = String } typealias Amb = Amb1 & Amb2 let _: Int.Type = Amb.T.self let _: String.Type = Amb.T.self
99ae3528f8e4916ba478877f22d74ac1
22.662461
173
0.679643
false
false
false
false
somegeekintn/SimDirs
refs/heads/main
SimDirs/Presentation/SourceState.swift
mit
1
// // SourceState.swift // SimDirs // // Created by Casey Fleser on 6/21/22. // import Foundation import Combine class SourceState: ObservableObject { typealias ProductFamily = SourceItemVal<SimProductFamily, DeviceType_DS> typealias Platform = SourceItemVal<SimPlatform, Runtime_RT> typealias DeviceType_DS = SourceItemVal<SimDeviceType, Runtime_DS> typealias DeviceType_RT = SourceItemVal<SimDeviceType, Device> typealias Runtime_DS = SourceItemVal<SimRuntime, Device> typealias Runtime_RT = SourceItemVal<SimRuntime, DeviceType_RT> typealias Device = SourceItemVal<SimDevice, App> typealias App = SourceItemVal<SimApp, SourceItemNone> enum Base: Identifiable { case placeholder(id: UUID = UUID()) case device(id: UUID = UUID(), SourceItemVal<SourceItemDataNone, ProductFamily>) case runtime(id: UUID = UUID(), SourceItemVal<SourceItemDataNone, Platform>) var id : UUID { switch self { case let .placeholder(id): return id case let .device(id, _): return id case let .runtime(id, _): return id } } } enum Style: Int, CaseIterable, Identifiable { case placeholder case byDevice case byRuntime var id : Int { rawValue } var title : String { switch self { case .placeholder: return "Placeholder" case .byDevice: return "By Device" case .byRuntime: return "By Runtime" } } var visible : Bool { switch self { case .placeholder: return false default: return true } } } @Published var style = Style.placeholder { didSet { rebuildBase() } } @Published var filter = SourceFilter.restore() { didSet { applyFilter() } } @Published var selection : UUID? var model : SimModel var base = Base.placeholder() var deviceUpdates : Cancellable? var filterApps : Bool { get { filter.options.contains(.withApps) } set { filter.options.booleanSet(newValue, options: .withApps) } } var filterRuntimes : Bool { get { filter.options.contains(.runtimeInstalled) } set { filter.options.booleanSet(newValue, options: .runtimeInstalled) } } init(model: SimModel) { self.style = .byDevice self.model = model self.rebuildBase() deviceUpdates = model.deviceUpdates.sink(receiveValue: applyDeviceUpdates) } func applyDeviceUpdates(_ updates: SimDevicesUpdates) { switch base { case .placeholder: break case let .device(_, item): for prodFamily in item.children { for devType in prodFamily.children { for runtime in devType.children { guard updates.runtime.identifier == runtime.data.identifier else { continue } let devTypeDevices = updates.additions.filter { $0.isDeviceOfType(devType.data) } runtime.children = runtime.children.filter { device in !updates.removals.contains { $0.udid == device.data.udid } } runtime.children.append(contentsOf: devTypeDevices.map { device in let imageDesc = devType.imageDesc.withColor(device.isAvailable ? .green : .red) return Device(data: device, children: device.apps.map { app in App(data: app, children: []) }, customImgDesc: imageDesc) }) } } } case let .runtime(_, item): for platform in item.children { for runtime in platform.children { guard updates.runtime.identifier == runtime.data.identifier else { continue } for devType in runtime.children { let devTypeDevices = updates.additions.filter { $0.isDeviceOfType(devType.data) } devType.children = devType.children.filter { device in !updates.removals.contains { $0.udid == device.data.udid } } devType.children.append(contentsOf: devTypeDevices.map { device in let imageDesc = devType.imageDesc.withColor(device.isAvailable ? .green : .red) return Device(data: device, children: device.apps.map { app in App(data: app, children: []) }, customImgDesc: imageDesc) }) } } } } applyFilter() } func applyFilter() { switch base { case .placeholder: break case let .device(_, item): item.applyFilter(filter) case let .runtime(_, item): item.applyFilter(filter) } } func rebuildBase() { var baseID : UUID // Preserve identifier if style is not changing switch (style, base) { case (.placeholder, let .placeholder(id)): baseID = id; case (.byDevice, let .device(id, _)): baseID = id; case (.byRuntime, let .runtime(id, _)): baseID = id; default: baseID = UUID() } switch style { case .placeholder: base = .placeholder(id: baseID) case .byDevice: base = .device(id: baseID, SourceItemVal(data: .none, children: deviceStyleItems())) case .byRuntime: base = .runtime(id: baseID, SourceItemVal(data: .none, children: runtimeStyleItems())) } applyFilter() } func baseFor(style: Style) -> Base { switch style { case .placeholder: return .placeholder() case .byDevice: return .device(SourceItemVal(data: .none, children: deviceStyleItems())) case .byRuntime: return .runtime(SourceItemVal(data: .none, children: runtimeStyleItems())) } } func deviceStyleItems() -> [ProductFamily] { SimProductFamily.presentation.map { family in ProductFamily(data: family, children: model.deviceTypes.supporting(productFamily: family).map { devType in DeviceType_DS(data: devType, children: model.runtimes.supporting(deviceType: devType).map { runtime in Runtime_DS(data: runtime, children: runtime.devices.of(deviceType: devType).map { device in let imageDesc = devType.imageDesc.withColor(device.isAvailable ? .green : .red) return Device(data: device, children: device.apps.map { app in App(data: app, children: []) }, customImgDesc: imageDesc) }) }) }) } } func runtimeStyleItems() -> [Platform] { SimPlatform.presentation.map { platform in Platform(data: platform, children: model.runtimes.supporting(platform: platform).map { runtime in Runtime_RT(data: runtime, children: model.deviceTypes.supporting(runtime: runtime).map { devType in DeviceType_RT(data: devType, children: runtime.devices.of(deviceType: devType).map { device in let imageDesc = devType.imageDesc.withColor(device.isAvailable ? .green : .red) return Device(data: device, children: device.apps.map { app in App(data: app, children: []) }, customImgDesc: imageDesc) }) }) }) } } }
0d440a4436c6c19db6e8b77f86ce0f7f
40.842932
152
0.546922
false
false
false
false
LoveZYForever/HXWeiboPhotoPicker
refs/heads/master
Pods/HXPHPicker/Sources/HXPHPicker/Picker/View/DeniedAuthorizationView.swift
mit
1
// // DeniedAuthorizationView.swift // HXPHPickerExample // // Created by Slience on 2020/12/29. // Copyright © 2020 Silence. All rights reserved. // import UIKit class DeniedAuthorizationView: UIView { let config: NotAuthorizedConfiguration lazy var navigationBar: UINavigationBar = { let navigationBar = UINavigationBar.init() navigationBar.setBackgroundImage( UIImage.image( for: UIColor.clear, havingSize: CGSize.zero ), for: UIBarMetrics.default ) navigationBar.shadowImage = UIImage.init() let navigationItem = UINavigationItem.init() navigationItem.leftBarButtonItem = UIBarButtonItem.init(customView: closeBtn) navigationBar.pushItem(navigationItem, animated: false) return navigationBar }() lazy var closeBtn: UIButton = { let closeBtn = UIButton.init(type: .custom) closeBtn.size = CGSize(width: 50, height: 40) closeBtn.addTarget(self, action: #selector(didCloseClick), for: .touchUpInside) closeBtn.contentHorizontalAlignment = .left return closeBtn }() lazy var titleLb: UILabel = { let titleLb = UILabel.init() titleLb.textAlignment = .center titleLb.numberOfLines = 0 return titleLb }() lazy var subTitleLb: UILabel = { let subTitleLb = UILabel.init() subTitleLb.textAlignment = .center subTitleLb.numberOfLines = 0 return subTitleLb }() lazy var jumpBtn: UIButton = { let jumpBtn = UIButton.init(type: .custom) jumpBtn.layer.cornerRadius = 5 jumpBtn.addTarget(self, action: #selector(jumpSetting), for: .touchUpInside) return jumpBtn }() init(config: NotAuthorizedConfiguration) { self.config = config super.init(frame: CGRect.zero) configView() } func configView() { if !config.hiddenCloseButton { addSubview(navigationBar) } addSubview(titleLb) addSubview(subTitleLb) addSubview(jumpBtn) titleLb.text = "无法访问相册中照片".localized titleLb.font = UIFont.semiboldPingFang(ofSize: 20) subTitleLb.text = "当前无照片访问权限,建议前往系统设置,\n允许访问「照片」中的「所有照片」。".localized subTitleLb.font = UIFont.regularPingFang(ofSize: 17) jumpBtn.setTitle("前往系统设置".localized, for: .normal) jumpBtn.titleLabel?.font = UIFont.mediumPingFang(ofSize: 16) configColor() } func configColor() { let closeButtonImageName = config.closeButtonImageName let closeButtonDarkImageName = config.closeButtonDarkImageName let isDark = PhotoManager.isDark closeBtn.setImage(UIImage.image(for: isDark ? closeButtonDarkImageName : closeButtonImageName), for: .normal) backgroundColor = isDark ? config.darkBackgroundColor : config.backgroundColor titleLb.textColor = isDark ? config.titleDarkColor : config.titleColor subTitleLb.textColor = isDark ? config.darkSubTitleColor : config.subTitleColor jumpBtn.backgroundColor = isDark ? config.jumpButtonDarkBackgroundColor : config.jumpButtonBackgroundColor jumpBtn.setTitleColor(isDark ? config.jumpButtonTitleDarkColor : config.jumpButtonTitleColor, for: .normal) } @objc func didCloseClick() { self.viewController?.dismiss(animated: true, completion: nil) } @objc func jumpSetting() { PhotoTools.openSettingsURL() } override func layoutSubviews() { super.layoutSubviews() var barHeight: CGFloat = 0 var barY: CGFloat = 0 if let pickerController = viewController as? PhotoPickerController { barHeight = pickerController.navigationBar.height if pickerController.modalPresentationStyle == .fullScreen { barY = UIDevice.statusBarHeight } } navigationBar.frame = CGRect(x: 0, y: barY, width: width, height: barHeight) let titleHeight = titleLb.text?.height(ofFont: titleLb.font, maxWidth: width) ?? 0 titleLb.frame = CGRect(x: 0, y: 0, width: width, height: titleHeight) let subTitleHeight = subTitleLb.text?.height(ofFont: subTitleLb.font, maxWidth: width - 40) ?? 0 let subTitleY: CGFloat if barHeight == 0 { subTitleY = height / 2 - subTitleHeight }else { subTitleY = height / 2 - subTitleHeight - 30 - UIDevice.topMargin } subTitleLb.frame = CGRect( x: 20, y: subTitleY, width: width - 40, height: subTitleHeight ) titleLb.y = subTitleLb.y - 15 - titleHeight let jumpBtnBottomMargin: CGFloat = UIDevice.isProxy() ? 120 : 50 var jumpBtnWidth = (jumpBtn.currentTitle?.width(ofFont: jumpBtn.titleLabel!.font, maxHeight: 40) ?? 0 ) + 10 if jumpBtnWidth < 150 { jumpBtnWidth = 150 } let jumpY: CGFloat if barHeight == 0 { jumpY = height - UIDevice.bottomMargin - 50 }else { jumpY = height - UIDevice.bottomMargin - 40 - jumpBtnBottomMargin } jumpBtn.frame = CGRect( x: 0, y: jumpY, width: jumpBtnWidth, height: 40 ) jumpBtn.centerX = width * 0.5 } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) if #available(iOS 13.0, *) { if traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) { configColor() } } } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
dc48c12ce6a9e5dd438e62b872f20351
35.158537
117
0.623272
false
true
false
false
RDCEP/psims
refs/heads/release-2.0
aggregate.swift
agpl-3.0
1
type file; app (external e) aggregate (string rundir, string param, string var, int chunk) { aggregate "-i" rundir "-p" param "-v" var "-c" chunk; } string cwd = arg("cwd"); string param = arg("param"); string vars[] = strsplit(strcat(arg("variables"), ",", arg("cal_vars")), ","); int numchunks = toInt(arg("num_chunks")); tracef("\nRunning aggregate . . .\n"); foreach var in vars { foreach chunk in [1 : numchunks] { external e; e = aggregate(cwd, param, var, chunk); } }
7f5e0c781414c060b6bc3a5cfe8cdded
27.333333
81
0.605882
false
false
false
false
binarylevel/Tinylog-iOS
refs/heads/master
Tinylog/Views/Keyboard/TLIKeyboardBar.swift
mit
1
// // TLIKeyboardBar.swift // Tinylog // // Created by Spiros Gerokostas on 18/10/15. // Copyright © 2015 Spiros Gerokostas. All rights reserved. // import UIKit class TLIKeyboardBar: UIView, UIInputViewAudioFeedback { var keyInputView:UIKeyInput? let buttonHashTag:UIButton = UIButton() let buttonMention:UIButton = UIButton() var enableInputClicksWhenVisible: Bool { return true } override init(frame: CGRect) { super.init(frame: frame) self.autoresizingMask = UIViewAutoresizing.FlexibleWidth self.backgroundColor = UIColor.tinylogNavigationBarDayColor() buttonHashTag.titleLabel!.font = UIFont(name: "HelveticaNeue", size: 20.0) buttonHashTag.setTitleColor(UIColor.tinylogMainColor(), forState: UIControlState.Normal) buttonHashTag.setTitle("#", forState: UIControlState.Normal) buttonHashTag.addTarget(self, action: #selector(TLIKeyboardBar.buttonHashTagPressed(_:)), forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(buttonHashTag) buttonMention.titleLabel!.font = UIFont(name: "HelveticaNeue", size: 20.0) buttonMention.setTitleColor(UIColor.tinylogMainColor(), forState: UIControlState.Normal) buttonMention.setTitle("@", forState: UIControlState.Normal) buttonMention.addTarget(self, action: #selector(TLIKeyboardBar.buttonMentionPressed(_:)), forControlEvents: UIControlEvents.TouchUpInside) self.addSubview(buttonMention) } required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() buttonHashTag.frame = CGRectMake(20.0, 1.0, 20.0, self.bounds.size.height - 1.0) buttonMention.frame = CGRectMake(60.0, 1.0, 20.0, self.bounds.size.height - 1.0) } func buttonHashTagPressed(button:UIButton) { UIDevice.currentDevice().playInputClick() keyInputView?.insertText("#") } func buttonMentionPressed(button:UIButton) { UIDevice.currentDevice().playInputClick() keyInputView?.insertText("@") } }
b1ff64ad02a6af33f5518c0361f78eba
36.305085
146
0.692867
false
false
false
false
SusanDoggie/Doggie
refs/heads/main
Sources/DoggieGraphics/ImageContext/DrawShadow.swift
mit
1
// // DrawShadow.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // extension ImageContext { @inlinable @inline(__always) var isShadow: Bool { return shadowColor.opacity > 0 && shadowBlur > 0 } @inlinable @inline(__always) func _drawWithShadow(stencil: MappedBuffer<Float>, color: Float32ColorPixel<Pixel.Model>) { let width = self.width let height = self.height let convolutionAlgorithm = self.convolutionAlgorithm let shadowColor = Float32ColorPixel(self.shadowColor.convert(to: colorSpace, intent: renderingIntent)) let shadowOffset = self.shadowOffset let shadowBlur = self.shadowBlur let filter = GaussianBlurFilter(Float(0.5 * shadowBlur)) let _offset = Point(x: Double(filter.count >> 1) - shadowOffset.width, y: Double(filter.count >> 1) - shadowOffset.height) let shadow_layer = StencilTexture(width: width, height: height, resamplingAlgorithm: .linear, pixels: stencil).convolution(horizontal: filter, vertical: filter, algorithm: convolutionAlgorithm) stencil.withUnsafeBufferPointer { stencil in guard var stencil = stencil.baseAddress else { return } self._withUnsafePixelBlender { blender in var blender = blender for y in 0..<height { for x in 0..<width { blender.draw { () -> Float32ColorPixel<Pixel.Model>? in let _shadow = shadow_layer.pixel(Point(x: x, y: y) + _offset) guard _shadow > 0 else { return nil } var shadowColor = shadowColor shadowColor._opacity *= _shadow return shadowColor } blender.draw { () -> Float32ColorPixel<Pixel.Model> in var color = color color._opacity *= stencil.pointee return color } blender += 1 stencil += 1 } } } } } @inlinable @inline(__always) func _drawWithShadow(texture: Texture<Pixel>) { let width = self.width let height = self.height let convolutionAlgorithm = self.convolutionAlgorithm let shadowColor = Float32ColorPixel(self.shadowColor.convert(to: colorSpace, intent: renderingIntent)) let shadowOffset = self.shadowOffset let shadowBlur = self.shadowBlur let filter = GaussianBlurFilter(Float(0.5 * shadowBlur)) let _offset = Point(x: Double(filter.count >> 1) - shadowOffset.width, y: Double(filter.count >> 1) - shadowOffset.height) var shadow_layer = StencilTexture<Float>(texture: texture).convolution(horizontal: filter, vertical: filter, algorithm: convolutionAlgorithm) shadow_layer.resamplingAlgorithm = .linear texture.withUnsafeBufferPointer { source in guard var source = source.baseAddress else { return } self._withUnsafePixelBlender { blender in var blender = blender for y in 0..<height { for x in 0..<width { blender.draw { () -> Float32ColorPixel<Pixel.Model>? in let _shadow = shadow_layer.pixel(Point(x: x, y: y) + _offset) guard _shadow > 0 else { return nil } var shadowColor = shadowColor shadowColor._opacity *= _shadow return shadowColor } blender.draw { source.pointee } blender += 1 source += 1 } } } } } }
8d543d7588813fe9643aaee7296dfbba
41.117188
201
0.55166
false
false
false
false
aducret/vj-ios-tp2
refs/heads/master
Shooter/Shooter/GameScene.swift
mit
1
// // GameScene.swift // Shooter // // Created by Argentino Ducret on 6/7/17. // Copyright © 2017 ITBA. All rights reserved. // import SpriteKit import GameplayKit class GameScene: SKScene { private var label : SKLabelNode? private var spinnyNode : SKShapeNode? override func didMove(to view: SKView) { // Get label node from scene and store it for use later self.label = self.childNode(withName: "//helloLabel") as? SKLabelNode if let label = self.label { label.alpha = 0.0 label.run(SKAction.fadeIn(withDuration: 2.0)) } // Create shape node to use during mouse interaction let w = (self.size.width + self.size.height) * 0.05 self.spinnyNode = SKShapeNode.init(rectOf: CGSize.init(width: w, height: w), cornerRadius: w * 0.3) if let spinnyNode = self.spinnyNode { spinnyNode.lineWidth = 2.5 spinnyNode.run(SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(Double.pi), duration: 1))) spinnyNode.run(SKAction.sequence([SKAction.wait(forDuration: 0.5), SKAction.fadeOut(withDuration: 0.5), SKAction.removeFromParent()])) } } func touchDown(atPoint pos : CGPoint) { if let n = self.spinnyNode?.copy() as! SKShapeNode? { n.position = pos n.strokeColor = SKColor.green self.addChild(n) } } func touchMoved(toPoint pos : CGPoint) { if let n = self.spinnyNode?.copy() as! SKShapeNode? { n.position = pos n.strokeColor = SKColor.blue self.addChild(n) } } func touchUp(atPoint pos : CGPoint) { if let n = self.spinnyNode?.copy() as! SKShapeNode? { n.position = pos n.strokeColor = SKColor.red self.addChild(n) } } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { if let label = self.label { label.run(SKAction.init(named: "Pulse")!, withKey: "fadeInOut") } for t in touches { self.touchDown(atPoint: t.location(in: self)) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchMoved(toPoint: t.location(in: self)) } } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchUp(atPoint: t.location(in: self)) } } override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) { for t in touches { self.touchUp(atPoint: t.location(in: self)) } } override func update(_ currentTime: TimeInterval) { // Called before each frame is rendered } }
229f887575e3f897af98ff973fc36961
31.876404
109
0.572454
false
false
false
false
Hyfenglin/bluehouseapp
refs/heads/master
iOS/post/post/AppDelegate.swift
mit
1
// // AppDelegate.swift // post // // Created by Derek Li on 14-10-8. // Copyright (c) 2014年 Derek Li. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.backgroundColor = UIColor.whiteColor() let postVC = PostViewController() let nav1 = UINavigationController(rootViewController: postVC) //let image1 = UIImage(named: "user_tabbar.png"); nav1.tabBarItem = UITabBarItem(title: "论坛列表", image: nil,tag:1) let userVC = UserViewController() let nav2 = UINavigationController(rootViewController: userVC) //let image2 = UIImage(named: "comment_tabbar.png"); nav2.tabBarItem = UITabBarItem(title: "用户信息", image: nil,tag:2) let navArr = [nav1,nav2] // let addPostVC = AddPostViewController() // let nav3 = UINavigationController(rootViewController: addPostVC) // //let image2 = UIImage(named: "comment_tabbar.png"); // nav3.tabBarItem = UITabBarItem(title: "添加帖子", image: nil,tag:3) // // let navArr = [nav1,nav2,nav3] let tabBarController = UITabBarController() tabBarController.viewControllers = navArr self.window!.rootViewController = tabBarController self.window!.makeKeyAndVisible() return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
07fdbf934c801d9d0cc5488200a5f540
45.465753
285
0.700472
false
false
false
false
ArthurKK/adaptive-tab-bar
refs/heads/master
adaptive-tab-bar/Samples/adaptive-dates-tabbar/adaptive-tab-bar/AdaptiveController/AdaptiveButtonsStateManager.swift
mit
9
// // AdaptiveButtonsStateManager.swift // AdaptiveTabBarControllerSample // // Created by Arcilite on 18.09.14. // Copyright (c) 2014 Ramotion. All rights reserved. // import UIKit let countDaysToSmallTextState = 14 let countDaysToImageState = 30 let defaultInsets = UIEdgeInsetsMake(0, 0,0, 0) let defaultSmallTitleModeFont = UIFont(name: "Helvetica", size: 10.0) let defaultSmallTitleModeImageInsets = UIEdgeInsetsMake(0, 0, 0, 0) let defaultImageModeInsets = UIEdgeInsetsMake(6, 0, -6, 0) let defaultSmallTitleModeOffset = UIOffsetMake(0, 20) let defaultOffset = UIOffsetMake(0, 00) let tabColor = UIColor(red: 169/255, green: 79/255, blue: 152/255, alpha: 1.0) @objc protocol AdaptiveApperanceProtocol { optional func setFontToAdaptiveButton(font: UIFont) optional func setTitleToAdaptiveButton(text: NSString) optional func setImageToAdaptiveButton(image: UIImage?) optional func setHighlightedToAdaptiveButton(image: UIImage?) optional func setBackgroundImageToAdaptiveButton(image: UIImage?) optional func setSelectedImageToAdaptiveButton(image: UIImage?) optional func setImageInsetsToAdaptiveButton(insets: UIEdgeInsets) optional func setTitleOffsetToAdaptiveButton(offset: UIOffset) optional func setTitleColorToAdaptiveButton(titleColor: UIColor) } let selected = "Selected" let highlighted = "Higlihted" class AdaptiveButtonsStateManager: NSObject { convenience init (state:AdaptiveState,buttonsAray:[AdaptiveApperanceProtocol],buttonsApperance:[AdaptiveButtonApperance]){ self.init() self.setButtonsState(state, buttonsAray: buttonsAray, buttonsApperance: buttonsApperance) } func setButtonsState(state:AdaptiveState,buttonsAray:[AdaptiveApperanceProtocol],buttonsApperance:[AdaptiveButtonApperance]){ var state:String = state.currentItemState! var countElements = buttonsAray.count > buttonsApperance.count ? buttonsApperance.count : buttonsAray.count for var index = 0; index < countElements; ++index { println("index is \(index)") println("buttons count array is \(buttonsAray.count)") var button :AdaptiveApperanceProtocol = buttonsAray[index] var buttonApperance = buttonsApperance[index] button.setTitleToAdaptiveButton!(buttonApperance.getButonTitleForState(state)) button.setFontToAdaptiveButton!(buttonApperance.getButonTitleFontForState(state)) if let image = buttonApperance.getButonImageForState(state) { button.setImageToAdaptiveButton?(image) } if let selectedImage = buttonApperance.getButonImageForState(state+selected) { button.setSelectedImageToAdaptiveButton?(selectedImage) } if let highlightedImage = buttonApperance.getButonImageForState(state+highlighted) { button.setHighlightedToAdaptiveButton?(highlightedImage) } if let backgroundImage = buttonApperance.getButonImageForState(state) { button.setBackgroundImageToAdaptiveButton?(backgroundImage) } if let imageInset = buttonApperance.getImageInsetsForState(state) { button.setImageInsetsToAdaptiveButton?(imageInset) } if let titleOffset = buttonApperance.getTitleOffsetForState(state) { button.setTitleOffsetToAdaptiveButton?(titleOffset) } if let titleColor = buttonApperance.getTitleColorForState(state) { button.setTitleColorToAdaptiveButton?(titleColor) } } } }
bfb2168c9c84ce8a4866faed4a5fd206
39.244681
130
0.695215
false
false
false
false
velvetroom/columbus
refs/heads/master
Source/GenericExtensions/ExtensionNSLayoutConstraint.swift
mit
1
import UIKit extension NSLayoutConstraint { @discardableResult class func topToTop( view:UIView, toView:UIView, constant:CGFloat = 0, multiplier:CGFloat = 1) -> NSLayoutConstraint { let constraint:NSLayoutConstraint = NSLayoutConstraint( item:view, attribute:NSLayoutAttribute.top, relatedBy:NSLayoutRelation.equal, toItem:toView, attribute:NSLayoutAttribute.top, multiplier:multiplier, constant:constant) constraint.isActive = true return constraint } @discardableResult class func topToBottom( view:UIView, toView:UIView, constant:CGFloat = 0, multiplier:CGFloat = 1) -> NSLayoutConstraint { let constraint:NSLayoutConstraint = NSLayoutConstraint( item:view, attribute:NSLayoutAttribute.top, relatedBy:NSLayoutRelation.equal, toItem:toView, attribute:NSLayoutAttribute.bottom, multiplier:multiplier, constant:constant) constraint.isActive = true return constraint } @discardableResult class func bottomToBottom( view:UIView, toView:UIView, constant:CGFloat = 0, multiplier:CGFloat = 1) -> NSLayoutConstraint { let constraint:NSLayoutConstraint = NSLayoutConstraint( item:view, attribute:NSLayoutAttribute.bottom, relatedBy:NSLayoutRelation.equal, toItem:toView, attribute:NSLayoutAttribute.bottom, multiplier:multiplier, constant:constant) constraint.isActive = true return constraint } @discardableResult class func bottomToTop( view:UIView, toView:UIView, constant:CGFloat = 0, multiplier:CGFloat = 1) -> NSLayoutConstraint { let constraint:NSLayoutConstraint = NSLayoutConstraint( item:view, attribute:NSLayoutAttribute.bottom, relatedBy:NSLayoutRelation.equal, toItem:toView, attribute:NSLayoutAttribute.top, multiplier:multiplier, constant:constant) constraint.isActive = true return constraint } @discardableResult class func leftToLeft( view:UIView, toView:UIView, constant:CGFloat = 0, multiplier:CGFloat = 1) -> NSLayoutConstraint { let constraint:NSLayoutConstraint = NSLayoutConstraint( item:view, attribute:NSLayoutAttribute.left, relatedBy:NSLayoutRelation.equal, toItem:toView, attribute:NSLayoutAttribute.left, multiplier:multiplier, constant:constant) constraint.isActive = true return constraint } @discardableResult class func leftToRight( view:UIView, toView:UIView, constant:CGFloat = 0, multiplier:CGFloat = 1) -> NSLayoutConstraint { let constraint:NSLayoutConstraint = NSLayoutConstraint( item:view, attribute:NSLayoutAttribute.left, relatedBy:NSLayoutRelation.equal, toItem:toView, attribute:NSLayoutAttribute.right, multiplier:multiplier, constant:constant) constraint.isActive = true return constraint } @discardableResult class func rightToRight( view:UIView, toView:UIView, constant:CGFloat = 0, multiplier:CGFloat = 1) -> NSLayoutConstraint { let constraint:NSLayoutConstraint = NSLayoutConstraint( item:view, attribute:NSLayoutAttribute.right, relatedBy:NSLayoutRelation.equal, toItem:toView, attribute:NSLayoutAttribute.right, multiplier:multiplier, constant:constant) constraint.isActive = true return constraint } @discardableResult class func rightToLeft( view:UIView, toView:UIView, constant:CGFloat = 0, multiplier:CGFloat = 1) -> NSLayoutConstraint { let constraint:NSLayoutConstraint = NSLayoutConstraint( item:view, attribute:NSLayoutAttribute.right, relatedBy:NSLayoutRelation.equal, toItem:toView, attribute:NSLayoutAttribute.left, multiplier:multiplier, constant:constant) constraint.isActive = true return constraint } @discardableResult class func width( view:UIView, constant:CGFloat = 0, multiplier:CGFloat = 1) -> NSLayoutConstraint { let constraint:NSLayoutConstraint = NSLayoutConstraint( item:view, attribute:NSLayoutAttribute.width, relatedBy:NSLayoutRelation.equal, toItem:nil, attribute:NSLayoutAttribute.notAnAttribute, multiplier:multiplier, constant:constant) constraint.isActive = true return constraint } @discardableResult class func widthGreaterOrEqual( view:UIView, constant:CGFloat = 0, multiplier:CGFloat = 1) -> NSLayoutConstraint { let constraint:NSLayoutConstraint = NSLayoutConstraint( item:view, attribute:NSLayoutAttribute.width, relatedBy:NSLayoutRelation.greaterThanOrEqual, toItem:nil, attribute:NSLayoutAttribute.notAnAttribute, multiplier:multiplier, constant:constant) constraint.isActive = true return constraint } @discardableResult class func height( view:UIView, constant:CGFloat = 0, multiplier:CGFloat = 1) -> NSLayoutConstraint { let constraint:NSLayoutConstraint = NSLayoutConstraint( item:view, attribute:NSLayoutAttribute.height, relatedBy:NSLayoutRelation.equal, toItem:nil, attribute:NSLayoutAttribute.notAnAttribute, multiplier:multiplier, constant:constant) constraint.isActive = true return constraint } @discardableResult class func heightGreaterOrEqual( view:UIView, constant:CGFloat = 0, multiplier:CGFloat = 1) -> NSLayoutConstraint { let constraint:NSLayoutConstraint = NSLayoutConstraint( item:view, attribute:NSLayoutAttribute.height, relatedBy:NSLayoutRelation.greaterThanOrEqual, toItem:nil, attribute:NSLayoutAttribute.notAnAttribute, multiplier:multiplier, constant:constant) constraint.isActive = true return constraint } class func size( view:UIView, constant:CGFloat, multiplier:CGFloat = 1) { NSLayoutConstraint.width( view:view, constant:constant, multiplier:multiplier) NSLayoutConstraint.height( view:view, constant:constant, multiplier:multiplier) } @discardableResult class func width( view:UIView, toView:UIView, multiplier:CGFloat = 1) -> NSLayoutConstraint { let constraint:NSLayoutConstraint = NSLayoutConstraint( item:view, attribute:NSLayoutAttribute.width, relatedBy:NSLayoutRelation.equal, toItem:toView, attribute:NSLayoutAttribute.width, multiplier:multiplier, constant:0) constraint.isActive = true return constraint } @discardableResult class func height( view:UIView, toView:UIView, multiplier:CGFloat = 1) -> NSLayoutConstraint { let constraint:NSLayoutConstraint = NSLayoutConstraint( item:view, attribute:NSLayoutAttribute.height, relatedBy:NSLayoutRelation.equal, toItem:toView, attribute:NSLayoutAttribute.height, multiplier:multiplier, constant:0) constraint.isActive = true return constraint } class func equals( view:UIView, toView:UIView, margin:CGFloat = 0) { NSLayoutConstraint.topToTop( view:view, toView:toView, constant:margin) NSLayoutConstraint.bottomToBottom( view:view, toView:toView, constant:-margin) NSLayoutConstraint.leftToLeft( view:view, toView:toView, constant:margin) NSLayoutConstraint.rightToRight( view:view, toView:toView, constant:-margin) } class func equalsHorizontal( view:UIView, toView:UIView, margin:CGFloat = 0) { NSLayoutConstraint.leftToLeft( view:view, toView:toView, constant:margin) NSLayoutConstraint.rightToRight( view:view, toView:toView, constant:-margin) } class func equalsVertical( view:UIView, toView:UIView, margin:CGFloat = 0) { NSLayoutConstraint.topToTop( view:view, toView:toView, constant:margin) NSLayoutConstraint.bottomToBottom( view:view, toView:toView, constant:-margin) } }
ef361b6e93cb9a3b4197e735f8ea15b1
27.523121
63
0.577059
false
false
false
false
SuperAwesomeLTD/sa-mobile-sdk-ios
refs/heads/develop
Pod/Classes/UI/Interstitial/InterstitialAdViewController.swift
lgpl-3.0
1
// // InterstitialAdController.swift // SuperAwesome // // Created by Gunhan Sancar on 04/09/2020. // import UIKit class InterstitialAdViewController: UIViewController, Injectable { private lazy var imageProvider: ImageProviderType = dependencies.resolve() private lazy var orientationProvider: OrientationProviderType = dependencies.resolve() private var bannerView: BannerView? private var closeButton: UIButton? private let adResponse: AdResponse private let parentGateEnabled: Bool private let bumperPageEnabled: Bool private let closeButtonState: CloseButtonState private let testingEnabled: Bool private let orientation: Orientation // swiftlint:disable weak_delegate private let delegate: AdEventCallback? init(adResponse: AdResponse, parentGateEnabled: Bool, bumperPageEnabled: Bool, closeButtonState: CloseButtonState, testingEnabled: Bool, orientation: Orientation, delegate: AdEventCallback?) { self.adResponse = adResponse self.parentGateEnabled = parentGateEnabled self.bumperPageEnabled = bumperPageEnabled self.closeButtonState = closeButtonState self.testingEnabled = testingEnabled self.orientation = orientation self.delegate = delegate super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = Constants.backgroundGray configureBannerView() configureCloseButton() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) bannerView?.play() } override var shouldAutorotate: Bool { true } override var prefersStatusBarHidden: Bool { true } override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { .fade } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { orientationProvider.findSupportedOrientations(orientation, super.supportedInterfaceOrientations) } /// Method that is called to close the ad func close() { bannerView?.close() bannerView = nil dismiss(animated: true, completion: nil) } private func configureBannerView() { let bannerView = BannerView() bannerView.configure(adResponse: adResponse, delegate: delegate) { [weak self] in self?.closeButton?.isHidden = false } bannerView.setTestMode(testingEnabled) bannerView.setBumperPage(bumperPageEnabled) bannerView.setParentalGate(parentGateEnabled) bannerView.translatesAutoresizingMaskIntoConstraints = false view.addSubview(bannerView) NSLayoutConstraint.activate([ bannerView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 0), bannerView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: 0), bannerView.topAnchor.constraint(equalTo: view.topAnchor, constant: 0), bannerView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: 0) ]) self.bannerView = bannerView } private func configureCloseButton() { let button = UIButton() button.isHidden = closeButtonState != .visibleImmediately button.setTitle("", for: .normal) button.setImage(imageProvider.closeImage, for: .normal) button.addTarget(self, action: #selector(onCloseClicked), for: .touchUpInside) button.translatesAutoresizingMaskIntoConstraints = false button.accessibilityIdentifier = "closeButton" view.addSubview(button) NSLayoutConstraint.activate([ button.widthAnchor.constraint(equalToConstant: 40.0), button.heightAnchor.constraint(equalToConstant: 40.0), button.trailingAnchor.constraint(equalTo: view.safeTrailingAnchor, constant: 0), button.topAnchor.constraint(equalTo: view.safeTopAnchor, constant: 0) ]) self.closeButton = button } @objc private func onCloseClicked() { bannerView?.close() dismiss(animated: true) } }
e0ac0cf173a39b0a77039505ec1f59d9
33.256
104
0.695002
false
false
false
false
One-self/ZhihuDaily
refs/heads/master
ZhihuDaily/ZhihuDaily/AppDelegate.swift
mit
1
// // AppDelegate.swift // ZhihuDaily // // Created by Oneselfly on 2017/5/7. // Copyright © 2017年 Oneself. All rights reserved. // import MMDrawerController @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { setupUI() return true } } // MARK: - UI extension AppDelegate { fileprivate func setupUI() { window = UIWindow() window?.backgroundColor = UIColor.white let homeVC = ZDHomeViewController() let drawerController = MMDrawerController(center: ZDNavigationController(rootViewController: homeVC), leftDrawerViewController: ZDMenuViewController(), rightDrawerViewController: nil) drawerController?.openDrawerGestureModeMask = .all drawerController?.closeDrawerGestureModeMask = .all drawerController?.view.backgroundColor = UIColor.white UIApplication.shared.setStatusBarStyle(.lightContent, animated: false) window?.rootViewController = drawerController window?.makeKeyAndVisible() } }
92fda3eb41d40bec9782ffc230d17418
28.302326
191
0.694444
false
false
false
false
hrscy/TodayNews
refs/heads/master
News/News/Classes/Mine/Controller/UserDetailBottomPopController.swift
mit
1
// // UserDetailBottomPopController.swift // News // // Created by 杨蒙 on 2017/12/1. // Copyright © 2017年 hrscy. All rights reserved. // import UIKit class UserDetailBottomPopController: UIViewController, UITableViewDelegate, UITableViewDataSource { var children = [BottomTabChildren]() @IBOutlet weak var tableView: UITableView! /// 点击了一个 bottomTab var didSelectedChild: ((BottomTabChildren)->())? override func viewDidLoad() { super.viewDidLoad() tableView.register(UITableViewCell.self, forCellReuseIdentifier: "\(UITableViewCell.self)") } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return children.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "\(UITableViewCell.self)", for: indexPath) cell.selectionStyle = .none let child = children[indexPath.row] cell.textLabel?.text = child.name cell.textLabel?.textAlignment = .center cell.textLabel?.font = UIFont.systemFont(ofSize: 13) return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { NotificationCenter.default.post(name: NSNotification.Name(rawValue: MyPresentationControllerDismiss), object: nil) didSelectedChild?(children[indexPath.row]) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
154efc53e2821cf91ff439c527a01940
33.553191
122
0.695197
false
false
false
false
saturnboy/learning_spritekit_swift
refs/heads/master
LearningSpriteKit/LearningSpriteKit/GameScene.swift
mit
1
// // GameScene.swift // LearningSpriteKit // // Created by Justin on 12/1/14. // Copyright (c) 2014 SaturnBoy. All rights reserved. // import SpriteKit class GameScene: SKScene { let alien = SKSpriteNode(imageNamed: "alien1") override func didMoveToView(view: SKView) { println("GameScene: \(view.frame.size)") self.backgroundColor = UIColor(red: 0.1, green: 0.1, blue: 0.3, alpha: 1.0) self.addChild(self.alien) } override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { if let touch: AnyObject = touches.anyObject() { let loc = touch.locationInNode(self) println("touch: \(loc)") // move alien to touch pos self.alien.position = loc } } override func update(currentTime: CFTimeInterval) { //move it self.alien.position = CGPoint(x: self.alien.position.x + 1.0, y: self.alien.position.y + 1.0) // 1. move it faster //self.alien.position = CGPoint(x: self.alien.position.x + 2.0, // y: self.alien.position.y + 2.0) // 2. make it bigger, smaller //self.alien.xScale += 0.01 //self.alien.yScale += 0.01 // 3. make it rotate //self.alien.zRotation -= 0.01 // 4. make is disappear //self.alien.alpha -= 0.002 // 5. make it bounce at the edges... } }
36e037ca200f0bf41d826b7a97b75261
27.685185
83
0.527437
false
false
false
false
P9SOFT/HJPhotoAlbumManager
refs/heads/master
Samples/Sample/Sample/AlbumListViewController.swift
mit
1
// // AlbumListViewController.swift // Sample // // Created by Tae Hyun Na on 2016. 2. 25. // Copyright (c) 2014, P9 SOFT, Inc. All rights reserved. // // Licensed under the MIT license. import UIKit class AlbumListViewController: UIViewController { private var createAlbumButton:UIButton = UIButton(type: .custom) private var editAlbumButton:UIButton = UIButton(type: .custom) private var albumTableView:UITableView = UITableView(frame: .zero) override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(photoAlbumManagerReport(_:)), name: .P9PhotoAlbumManager, object: nil) automaticallyAdjustsScrollViewInsets = false; view.backgroundColor = UIColor.white createAlbumButton.setTitle("➕", for: .normal) createAlbumButton.addTarget(self, action: #selector(createAlbumButtonTouchUpInside(sender:)), for: .touchUpInside) createAlbumButton.isHidden = true editAlbumButton.setTitle("EDIT", for: .normal) editAlbumButton.setTitleColor(.black, for: .normal) editAlbumButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 12) editAlbumButton.addTarget(self, action: #selector(editAlbumButtonTouchUpInside(sender:)), for: .touchUpInside) albumTableView.register(UINib(nibName:"AlbumRecordTableViewCell", bundle:nil), forCellReuseIdentifier:"AlbumRecordTableViewCell") albumTableView.dataSource = self albumTableView.delegate = self albumTableView.backgroundColor = UIColor.clear view.addSubview(albumTableView) view.addSubview(createAlbumButton) view.addSubview(editAlbumButton) // request album list, and write code for result handling. // you can write code for result handling with response of notification handler 'photoAlbumManagerReport' as below. let cameraRoll = P9PhotoAlbumManager.AlbumInfo.init(type: .cameraRoll) let favorite = P9PhotoAlbumManager.AlbumInfo.init(type: .favorite) let recentlyAdded = P9PhotoAlbumManager.AlbumInfo.init(type: .recentlyAdded) let screenshots = P9PhotoAlbumManager.AlbumInfo.init(type: .screenshots) let videos = P9PhotoAlbumManager.AlbumInfo.init(type: .videos, mediaTypes: [.video], ascending: false) let regular = P9PhotoAlbumManager.AlbumInfo.init(type: .regular) let albumInfos = [cameraRoll, favorite, recentlyAdded, screenshots, videos, regular] if P9PhotoAlbumManager.shared.authorized == false { P9PhotoAlbumManager.shared.authorization { (operation, status) in if status == .succeed { P9PhotoAlbumManager.shared.requestAlbums(byInfos: albumInfos) { (operation, status) in self.albumTableView.reloadData() } } else { let alert = UIAlertController(title: "Need Authorization", message: "You need to move setting to give access authorization of photo for this app", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) self.present(alert, animated: true, completion: nil) } } return; } P9PhotoAlbumManager.shared.requestAlbums(byInfos: albumInfos) { (operation, status) in self.albumTableView.reloadData() } } deinit { NotificationCenter.default.removeObserver(self) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) albumTableView.reloadData() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() var frame:CGRect = .zero frame.size = CGSize(width: 30, height: 30) frame.origin.x = 20 frame.origin.y = UIApplication.shared.statusBarFrame.size.height + 5 createAlbumButton.frame = frame frame.size = CGSize(width: 40, height: 30) frame.origin.x = self.view.bounds.size.width - 20 - frame.size.width frame.origin.y = UIApplication.shared.statusBarFrame.size.height + 5 editAlbumButton.frame = frame frame = self.view.bounds frame.origin.y += (UIApplication.shared.statusBarFrame.size.height + 40) frame.size.height -= (UIApplication.shared.statusBarFrame.size.height + 40) albumTableView.frame = frame } @objc func photoAlbumManagerReport(_ notification:Notification) { // you can write code as below for result handling, but in this case, just print log. // because we already pass the code for result handler when requesting data at 'viewDidLoad'. if let userInfo = notification.userInfo, let operation = userInfo[P9PhotoAlbumManager.NotificationOperationKey] as? P9PhotoAlbumManager.Operation, let status = userInfo[P9PhotoAlbumManager.NotificationStatusKey] as? P9PhotoAlbumManager.Status { print("Operatoin[\(operation.rawValue)], Status[\(status.rawValue)]") if operation == .reload { albumTableView.reloadData() } } } @objc func createAlbumButtonTouchUpInside(sender:UIButton) { let alert = UIAlertController(title: "Create Album", message: "Enter album title to create", preferredStyle: .alert) alert.addTextField { (textField) in textField.placeholder = "Album Title" textField.textColor = .black } alert.addAction(UIAlertAction(title: "Create", style: .default, handler: { (action) in if let textField = alert.textFields?.first, let title = textField.text { P9PhotoAlbumManager.shared.createAlbum(title: title, mediaTypes: [.image], ascending: false, completion: { (operation, status) in self.albumTableView.reloadData() }) } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(alert, animated: true, completion: nil) } @objc func editAlbumButtonTouchUpInside(sender:UIButton) { if albumTableView.isEditing == false { createAlbumButton.isHidden = false albumTableView.setEditing(true, animated: true) editAlbumButton.setTitle("DONE", for: .normal) } else { createAlbumButton.isHidden = true albumTableView.setEditing(false, animated: true) editAlbumButton.setTitle("EDIT", for: .normal) } } } extension AlbumListViewController: UITableViewDataSource, UITableViewDelegate { func numberOfSections(in tableView:UITableView) -> Int { return 1 } func tableView(_ tableView:UITableView, numberOfRowsInSection section:Int) -> Int { return P9PhotoAlbumManager.shared.numberOfAlbums() } func tableView(_ tableView:UITableView, heightForRowAt indexPath:IndexPath) -> CGFloat { return 80 } func tableView(_ tableView:UITableView, cellForRowAt indexPath:IndexPath) -> UITableViewCell { if let cell = albumTableView.dequeueReusableCell(withIdentifier: "AlbumRecordTableViewCell") as? AlbumRecordTableViewCell { cell.coverImageView.image = P9PhotoAlbumManager.shared.imageOfMedia(forIndex: 0, atAlbumIndex: indexPath.row, targetSize: CGSize.init(width: 80, height: 80), contentMode: .aspectFill) cell.titleLabel.text = P9PhotoAlbumManager.shared.titleOfAlbum(forIndex: indexPath.row) cell.countLabel.text = "\(P9PhotoAlbumManager.shared.numberOfMediaAtAlbum(forIndex: indexPath.row))" return cell } return UITableViewCell() } func tableView(_ tableView:UITableView, didSelectRowAt indexPath:IndexPath) { tableView.deselectRow(at: indexPath, animated:true) let photoListViewController = PhotoListViewController() photoListViewController.albumIndex = indexPath.row navigationController?.pushViewController(photoListViewController, animated:true) } func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { if let type = P9PhotoAlbumManager.shared.predefineTypeOfAlbum(forIndex: indexPath.row), type == .regular { return true } return false } func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle { if let type = P9PhotoAlbumManager.shared.predefineTypeOfAlbum(forIndex: indexPath.row), type == .regular { return .delete } return .none } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { P9PhotoAlbumManager.shared.deleteAlbum(index: indexPath.row) { (operation, status) in self.albumTableView.reloadData() } } } }
be2f612fb665861a0d58ccea3221fc49
42.219178
253
0.656947
false
false
false
false
pitput/SwiftWamp
refs/heads/master
SwiftWampTests/SwiftWebSocketLibConnectTests.swift
mit
1
// // SwiftWebSocketLibConnectTests.swift // SwiftWamp // // Created by Dany Sousa on 17/02/2017. // Copyright © 2017 danysousa. All rights reserved. // import XCTest @testable import SwiftWamp class SwiftWebSocketLibConnectTests: XCTestCase, SwampSessionDelegate { let socketUrl: String = "ws://localhost:8080/ws" let defaultRealm: String = "restrictive-realm" let authMethods: [String] = ["wampcra"] let authID: String = "homer" let goodCraSecret: String = "secret123" var craSecret: String = "secret123" var transport: SwiftWebSocketTransport? var session: SwampSession? var sessionID: NSNumber? = nil var subscription: [String: Subscription] = [:] var expectation: [String: XCTestExpectation] = [:] var startedDisconnectProcess: Bool = false var startedConnectProcess: Bool = false /** This function is called before all tests but it's a test too Create a session and try to connect to crossbar, and check if the connection is established */ override func setUp() { super.setUp() self.expectation = [:] self.transport = SwiftWebSocketTransport(wsEndpoint: self.socketUrl) self.transport?.enableDebug = true session = SwampSession(realm: self.defaultRealm, transport: transport!, authmethods: self.authMethods, authid: authID) session?.delegate = self } override func tearDown() { super.tearDown() if self.sessionID == nil { return } self.startedDisconnectProcess = true self.expectation["disconnectProcessEnded"] = expectation(description: "disconnectProcessEnded") session!.disconnect() waitForExpectations(timeout: 10, handler: { error in XCTAssertNil(error) self.startedConnectProcess = false }) } func testWithGoodCra() { self.expectation["connectionProcessEnded"] = expectation(description: "connectionProcessEnded") self.startedConnectProcess = true self.session!.connect() waitForExpectations(timeout: 10, handler: { error in XCTAssertTrue(self.session!.isConnected()) XCTAssertNotNil(self.sessionID) self.startedConnectProcess = false }) } func testWithBadCra() { self.craSecret = "pokpok" self.expectation["connectionProcessEnded"] = expectation(description: "connectionProcessEnded") self.startedConnectProcess = true self.session!.connect() waitForExpectations(timeout: 10, handler: { error in XCTAssertFalse(self.session!.isConnected()) XCTAssertNil(self.sessionID) self.startedConnectProcess = false }) } func swampSessionHandleChallenge(_ authMethod: String, extra: [String: Any]) -> String { return SwampCraAuthHelper.sign(self.craSecret, challenge: extra["challenge"] as! String) } func swampSessionConnected(_ session: SwampSession, sessionId: NSNumber) { self.sessionID = sessionId if self.craSecret != self.goodCraSecret { XCTFail() } self.expectation["connectionProcessEnded"]?.fulfill() } func swampSessionEnded(_ reason: String) { if self.startedDisconnectProcess { self.expectation["disconnectProcessEnded"]?.fulfill() XCTAssertEqual(reason, "wamp.close.normal") return } else if self.startedConnectProcess { self.expectation["connectionProcessEnded"]?.fulfill() if self.craSecret == self.goodCraSecret { XCTFail() } return } // Unexpected disconnection XCTFail() } }
37dbb4ed031cbc26e7b4ffdbb7cba9ab
31.301724
126
0.648786
false
true
false
false
fantast1k/Swiftent
refs/heads/master
Swiftent/Swiftent/Source/UIKit/UIButtonContent.swift
gpl-3.0
1
// // UIButtonContent.swift // Swiftent // // Created by Dmitry Fa[n]tastik on 18/07/2016. // Copyright © 2016 Fantastik Solution. All rights reserved. // import Foundation public struct UIButtonContent { let normal : UIButtonStateContent? let highlighted : UIButtonStateContent? let disabled : UIButtonStateContent? let selected : UIButtonStateContent? public init(normal: UIButtonStateContent?, highlighted: UIButtonStateContent?, disabled: UIButtonStateContent?, selected: UIButtonStateContent?) { self.normal = normal self.highlighted = highlighted self.disabled = disabled self.selected = selected } public init(normal: UIButtonStateContent?) { self.normal = normal self.highlighted = nil self.disabled = nil self.selected = nil } public init(normal: UIButtonStateContent?, selected: UIButtonStateContent?) { self.normal = normal self.selected = selected self.disabled = nil self.highlighted = nil } } public struct UIButtonStateContent { let text : Text let image : UIImage? let titleColor : UIColor? = nil let titleShadowColor : UIColor? = nil let backgroundImage : UIImage? = nil public init(text: Text, image: UIImage?) { self.text = text self.image = image } public init(text: Text) { self.text = text self.image = nil } public init(image: UIImage?) { self.text = Text.Raw(nil) self.image = image } public static let None = UIButtonStateContent(text: Text.Raw(nil), image: nil) }
f10743aa43172606108a1d3bab0b6a0b
24.530303
82
0.632641
false
false
false
false
exchangegroup/FitLoader
refs/heads/master
Demo/Core/PresentingViewControllers/TegPresentViewController.swift
mit
2
// // Present view controller modally using its storyboard ID. // import UIKit class TegPresentViewController { class func present(viewController: UIViewController, viewControllerName: TegViewControllerNames, beforePresenting: ((UIViewController)->())? = nil) -> UIViewController? { if let unwrapedViewController = instantiateViewControllerWithIdentifier(viewControllerName) { beforePresenting?(unwrapedViewController) viewController.presentViewController(unwrapedViewController, animated: true, completion: nil) return unwrapedViewController } return nil } class func pushToNavigationController(viewController: UIViewController, viewControllerName: TegViewControllerNames, animated: Bool = true, beforePresenting: ((UIViewController)->())? = nil) -> UIViewController? { if let unwrapedViewController = instantiateViewControllerWithIdentifier(viewControllerName) { beforePresenting?(unwrapedViewController) viewController.navigationController?.pushViewController(unwrapedViewController, animated: animated) return unwrapedViewController } return nil } class func instantiateViewControllerWithIdentifier(viewControllerName: TegViewControllerNames) -> UIViewController? { let storyboardName = viewControllerName.storyboardName let bundle = NSBundle.mainBundle() let storyboard = UIStoryboard(name: storyboardName.rawValue, bundle: bundle) return storyboard.instantiateViewControllerWithIdentifier(viewControllerName.rawValue) } }
992a37a7139a3bea37798ced55981575
32.87234
99
0.760678
false
false
false
false
17AustinZ/Poker-Chip
refs/heads/master
ALRadialMenu/ALRadialMenu.swift
mit
1
// // ALRadialMenu.swift // ALRadialMenu // // Created by Alex Littlejohn on 2015/04/26. // Copyright (c) 2015 zero. All rights reserved. // import UIKit private typealias ALAnimationsClosure = () -> Void private struct Angle { var degrees: Double func radians() -> Double { return degrees * (M_PI/180) } } public class ALRadialMenu: UIButton { // MARK: Public API public convenience init() { self.init(frame: CGRectZero) //overlayView = UIView(frame: CGRectMake(UIScreen.mainScreen().bounds.width / 2, UIScreen.mainScreen().bounds.height * 2 / 5, CGFloat(self.radius * 2), CGFloat(self.radius * 2))) } public override init(frame: CGRect) { super.init(frame: frame) commonInit() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) commonInit() } /** Set a delay to stagger the showing of each subsequent radial button Note: this is a bit buggy when using UIView animations Default = 0 :param: Double The delay in seconds */ public func setDelay(delay: Double) -> Self { self.delay = delay return self } /** Set the buttons to display when present is called. Each button should be an instance of ALRadialMenuButton :param: Array An array of ALRadialMenuButton instances */ public func setButtons(buttons: [ALRadialMenuButton]) -> Self { self.buttons = buttons for i in 0..<buttons.count { let button = buttons[i] let action = button.action button.center = center button.action = { button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal) button.imageEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0) if let a = action { a() } } } return self } /** Set to false to disable dismissing the menu on background tap Default = true :param: Bool enabled or disable the gesture */ public func setDismissOnOverlayTap(dismissOnOverlayTap: Bool) -> Self { self.dismissOnOverlayTap = dismissOnOverlayTap return self } /** Set the radius to control how far from the point of origin the buttons should show when the menu is open Default = 100 :param: Double the radius in pts */ public func setRadius(radius: Double) -> Self { self.radius = radius return self } /** Set the starting angle from which to lay out the buttons Default = 270 :param: Double the angle in degrees */ public func setStartAngle(degrees: Double) -> Self { self.startAngle = Angle(degrees: degrees) return self } /** Set the total circumference that the buttons should be laid out in Default = 360 :param: Double the circumference in degrees */ public func setCircumference(degrees: Double) -> Self { self.circumference = Angle(degrees: degrees) return self } /** Set the origin point from which the buttons should animate Default = self.center :param: CGPoint the origin point */ public func setAnimationOrigin(animationOrigin: CGPoint) -> Self { self.animationOrigin = animationOrigin return self } /** Present the buttons in the specified view's window :param: UIView view */ public func presentInView(view: UIView) -> Self { return presentInWindow(view.window!) } /** Present the buttons in the specified window :param: UIWindow window */ public func presentInWindow(win: UIWindow) -> Self { if buttons.count == 0 { println("ALRadialMenu has no buttons to present") return self } if animationOrigin == nil { animationOrigin = center } // win.addSubview(overlayView) for i in 0..<buttons.count { let button = buttons[i] win.addSubview(button) presentAnimation(button, index: i) } return self } public func refreshButtons(view: UIView){ var window = view.window if buttons.count == 0 { println("ALRadialMenu has no buttons to present") } if animationOrigin == nil { animationOrigin = center } for i in 0..<buttons.count { dismissWithoutAnimation(buttons[i], index: i) animationOrigin = center // view.window!.addSubview(overlayView) view.window!.addSubview(buttons[i]) presentWithoutAnimation(buttons[i], index: i) } } public func rotate(view: UIView){ var window = view.window for var i = buttons.count - 1; i >= 0; i-- { rotateButton(buttons[i], index: i-1) } println() rotateButton(buttons[0], index: buttons.count - 1) var tempButton = buttons.removeAtIndex(0) buttons.insert(tempButton, atIndex: buttons.count) } /** Dismiss the buttons with an animation */ public func dismiss() -> Self { if buttons.count == 0 { println("ALRadialMenu has no buttons to dismiss") return self } dismiss(-1) return self } // MARK: private vars private var delay: Double = 0 private var buttons = [ALRadialMenuButton]() { didSet { calculateSpacing() } } private var dismissOnOverlayTap = true { didSet { if let gesture = dismissGesture { gesture.enabled = dismissOnOverlayTap } } } // private var overlayView = UIView(frame: UIScreen.mainScreen().bounds) private var radius: Double = 100 private var startAngle: Angle = Angle(degrees: 270) private var circumference: Angle = Angle(degrees: 360) { didSet { calculateSpacing() } } private var spacingDegrees: Angle! private var animationOrigin: CGPoint! private var dismissGesture: UITapGestureRecognizer! private var animationOptions = UIViewAnimationOptions.CurveEaseInOut | UIViewAnimationOptions.BeginFromCurrentState // MARK: Private API private func commonInit() { // dismissGesture = UITapGestureRecognizer(target: self, action: "dismiss") // dismissGesture.enabled = dismissOnOverlayTap // // overlayView.addGestureRecognizer(dismissGesture) } private func dismiss(selectedIndex: Int) { // overlayView.removeFromSuperview() for i in 0..<buttons.count { if i == selectedIndex { selectedAnimation(buttons[i]) } else { dismissAnimation(buttons[i], index: i) } } } private func presentAnimation(view: ALRadialMenuButton, index: Int) { let degrees = startAngle.degrees + spacingDegrees.degrees * Double(index) let newCenter = pointOnCircumference(animationOrigin, radius: radius, angle: Angle(degrees: degrees)) let _delay = Double(index) * delay view.center = animationOrigin view.alpha = 0 UIView.animateWithDuration(0.5, delay: _delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: animationOptions, animations: { view.alpha = 1 view.center = newCenter }, completion: nil) } private func rotateButton(view: ALRadialMenuButton, index: Int){ let degrees = startAngle.degrees + spacingDegrees.degrees * Double(index) let newCenter = pointOnCircumference(animationOrigin, radius: radius, angle: Angle(degrees: degrees)) let _delay = Double(index) * delay //view.center = animationOrigin view.alpha = 0 UIView.animateWithDuration(0.5, delay: _delay, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: animationOptions, animations: { view.alpha = 1 view.center = newCenter }, completion: nil) } private func presentWithoutAnimation(view: ALRadialMenuButton, index: Int) { let degrees = startAngle.degrees + spacingDegrees.degrees * Double(index) let newCenter = pointOnCircumference(CGPoint(x: UIScreen.mainScreen().bounds.width / 2, y: UIScreen.mainScreen().bounds.height * 2 / 5), radius: radius, angle: Angle(degrees: degrees)) let _delay = Double(index) * delay view.alpha = 1 view.center = newCenter } private func dismissAnimation(view: ALRadialMenuButton, index: Int) { let _delay = Double(index) * delay UIView.animateWithDuration(0.5, delay: _delay, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: animationOptions, animations: { view.alpha = 0 view.center = self.animationOrigin }, completion: { finished in view.removeFromSuperview() }) } public func dismissWithoutAnimation(view: ALRadialMenuButton, index: Int) { view.removeFromSuperview() } private func selectedAnimation(view: ALRadialMenuButton) { UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.7, options: animationOptions, animations: { view.alpha = 0 view.transform = CGAffineTransformMakeScale(1.5, 1.5) }, completion: { finished in view.transform = CGAffineTransformIdentity view.removeFromSuperview() }) } private func pointOnCircumference(origin: CGPoint, radius: Double, angle: Angle) -> CGPoint { let radians = angle.radians() let x = origin.x + CGFloat(radius) * CGFloat(cos(radians)) let y = origin.y + CGFloat(radius) * CGFloat(sin(radians)) return CGPointMake(x, y) } private func calculateSpacing() { if buttons.count > 0 { var c = buttons.count if circumference.degrees < 360 { c-- } spacingDegrees = Angle(degrees: circumference.degrees / Double(c)) } } }
d56d7b2a1aeb7a96c3ee54c1bc5addf1
28.037838
192
0.586056
false
false
false
false
suncry/MLHybrid
refs/heads/master
Source/Content/Model/Hybrid_titleModel.swift
mit
1
// // Hybrid_titleModel.swift // Hybrid_Medlinker // // Created by caiyang on 16/5/13. // Copyright © 2016年 caiyang. All rights reserved. // import UIKit class Hybrid_titleModel: NSObject { var title: String = "" var subtitle: String = "" var tagname: String = "" var lefticon: String = "" var righticon: String = "" var placeholder: String = "" var callback: String = "" var focus: Bool = false class func convert(_ dic: [String: AnyObject]) -> Hybrid_titleModel { let titleModel = Hybrid_titleModel() titleModel.title = dic["title"] as? String ?? "" titleModel.subtitle = dic["subtitle"] as? String ?? "" titleModel.tagname = dic["tagname"] as? String ?? "" titleModel.lefticon = dic["lefticon"] as? String ?? "" titleModel.righticon = dic["righticon"] as? String ?? "" titleModel.placeholder = dic["placeholder"] as? String ?? "" titleModel.callback = dic["callback"] as? String ?? "" titleModel.focus = dic["focus"] as? Bool ?? false return titleModel } }
14e9b1891fffd5f2ece53ca01b544f56
30.342857
73
0.602552
false
false
false
false
thehung111/visearch-widget-swift
refs/heads/develop
ViSearchWidgets/ViSearchWidgets/ViColorSearchViewController.swift
mit
2
// // ViColorSearchViewController.swift // ViSearchWidgets // // Created by Hung on 25/11/16. // Copyright © 2016 Visenze. All rights reserved. // import UIKit import ViSearchSDK import LayoutKit /// Search by Color widget. Search results will be displayed in a grid open class ViColorSearchViewController: ViGridSearchViewController , UIPopoverPresentationControllerDelegate, ViColorPickerDelegate { /// Tag for the float view containing color picker + filter buttons /// The floating view will appear when we scroll down let floatViewTag : Int = 999 // default list of colors in the color picker in hex format e.g. e0b0ff, 2abab3 open var colorList: [String] = [ "000000" , "555555" , "9896a4" , "034f84" , "00afec" , "98ddde" , "00ffff" , "f5977d" , "91a8d0", "ea148c" , "f53321" , "d66565" , "ff00ff" , "a665a7" , "e0b0ff" , "f773bd" , "f77866" , "7a2f04" , "cc9c33" , "618fca" , "79c753" , "228622" , "4987ec" , "2abab3" , "ffffff" ] open override func setup(){ super.setup() self.title = "Search By Color" // hide this as we will use the query color picker self.showTitleHeader = false } /// layout for header that contains query product and filter open override var headerLayout : Layout? { var allLayouts : [Layout] = [] var colorLogoLayouts : [Layout] = [] // add color preview let colorPreviewLayout = SizeLayout<UIView>( width: 120, height: 120, alignment: .topLeading, flexibility: .inflexible, config: { v in if let colorParams = self.searchParams as? ViColorSearchParams { v.backgroundColor = UIColor.colorWithHexString(colorParams.color, alpha: 1.0) } } ) // wrap color preview and color picker icon let colorPickerEl = SizeLayout<UIButton>( width: ViIcon.color_pick!.width + 8, height: ViIcon.color_pick!.height + 8, alignment: .bottomTrailing , flexibility: .inflexible, viewReuseId: nil, config: { button in button.backgroundColor = ViTheme.sharedInstance.color_pick_btn_background_color button.setImage(ViIcon.color_pick, for: .normal) button.setImage(ViIcon.color_pick, for: .highlighted) button.tintColor = ViTheme.sharedInstance.color_pick_btn_tint_color button.imageEdgeInsets = UIEdgeInsetsMake( 4, 4, 4, 4) button.tag = ViProductCardTag.colorPickBtnTag.rawValue button.addTarget(self, action: #selector(self.openColorPicker), for: .touchUpInside) } ) let colorPreviewAndPickerLayout = StackLayout( axis: .horizontal, spacing: 2, sublayouts: [colorPreviewLayout , colorPickerEl] ) colorLogoLayouts.append(colorPreviewAndPickerLayout) if showPowerByViSenze { let powerByLayout = self.getPowerByVisenzeLayout() colorLogoLayouts.append(powerByLayout) } // add in the border view at bottom let divider = self.getDividerLayout() colorLogoLayouts.append(divider) let productAndLogoStackLayout = StackLayout( axis: .vertical, spacing: 2, sublayouts: colorLogoLayouts ) allLayouts.append(productAndLogoStackLayout) // label and filter layout let labelAndFilterLayout = self.getLabelAndFilterLayout(emptyProductsTxt: "Products Found", displayStringFormat: "%d Products Found") allLayouts.append(labelAndFilterLayout) let allStackLayout = StackLayout( axis: .vertical, spacing: 4, sublayouts: allLayouts ) let insetLayout = InsetLayout( insets: EdgeInsets(top: 8, left: 8, bottom: 8, right: 8), sublayout: allStackLayout ) return insetLayout } // MARK: Scroll methods open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) { self.checkHeaderGone(scrollView) } open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { self.checkHeaderGone(scrollView) } /// Create the floating view that contains Filter + Color Picker buttons /// /// - Returns: generated view public func getFloatingView() -> UIView { let floatView = UIView() floatView.tag = self.floatViewTag floatView.autoresizingMask = [ .flexibleLeftMargin , .flexibleRightMargin ] let btnWidth = ViIcon.color_pick!.width + 12 var floatWidth = btnWidth let button = UIButton(type: .custom) button.backgroundColor = ViTheme.sharedInstance.filter_btn_floating_background_color button.setImage(ViIcon.color_pick, for: .normal) button.setImage(ViIcon.color_pick, for: .highlighted) button.tintColor = ViTheme.sharedInstance.color_pick_btn_tint_color button.imageEdgeInsets = UIEdgeInsetsMake( 4, 4, 4, 4) button.tag = ViProductCardTag.colorPickBtnTag.rawValue button.frame = CGRect(x: 0, y: 0, width: btnWidth, height: btnWidth) button.addTarget(self, action: #selector(self.openColorPicker), for: .touchUpInside) floatView.addSubview(button) if false == self.filterBtn?.isHidden { // filter let filterButton = UIButton(type: .custom) filterButton.backgroundColor = ViTheme.sharedInstance.filter_btn_floating_background_color filterButton.setImage(ViIcon.filter, for: .normal) filterButton.setImage(ViIcon.filter, for: .highlighted) filterButton.tintColor = ViTheme.sharedInstance.filter_btn_tint_color filterButton.imageEdgeInsets = UIEdgeInsetsMake( 4, 4, 4, 4) filterButton.tag = ViProductCardTag.filterBtnTag.rawValue filterButton.addTarget(self, action: #selector(self.filterBtnTap), for: .touchUpInside) filterButton.frame = CGRect(x: btnWidth + 8, y: 0, width: btnWidth, height: btnWidth) floatWidth = filterButton.frame.origin.x + btnWidth floatView.addSubview(filterButton) } floatView.frame = CGRect(x: self.view.bounds.width - floatWidth - 8 , y: 0 , width: floatWidth , height: btnWidth ) return floatView } /// reset scroll and move collectionView back to top open func resetScroll() { self.collectionView?.contentOffset = .zero // hide filter btn if let floatView = self.view.viewWithTag(self.floatViewTag) { floatView.isHidden = true } } /// check scroll view position, if below header , then overlay filter + color buttons on top open func checkHeaderGone(_ scrollView: UIScrollView) { if self.headerLayoutHeight == 0 { return } var floatView : UIView? = self.view.viewWithTag(self.floatViewTag) if floatView == nil { floatView = self.getFloatingView() floatView?.isHidden = true self.view.addSubview(floatView!) self.view.bringSubview(toFront: floatView!) } if scrollView.contentOffset.y > self.headerLayoutHeight { floatView?.isHidden = false } else { floatView?.isHidden = true } } /// Open color picker view in a popover /// /// - Parameters: /// - sender: color picker button /// - event: button event public func openColorPicker(sender: UIButton, forEvent event: UIEvent) { let controller = ViColorPickerModalViewController() controller.modalPresentationStyle = .popover controller.delegate = self controller.colorList = self.colorList controller.paddingLeft = 8 controller.paddingRight = 8 controller.preferredContentSize = CGSize(width: self.view.bounds.width, height: 300) if( searchParams != nil && (searchParams is ViColorSearchParams) ) { if let colorParams = searchParams as? ViColorSearchParams { controller.selectedColor = colorParams.color } } if let popoverController = controller.popoverPresentationController { popoverController.sourceView = sender popoverController.sourceRect = sender.bounds popoverController.permittedArrowDirections = UIPopoverArrowDirection.any popoverController.delegate = self } self.present(controller, animated: true, completion: nil) } // important - this is needed so that a popover will be properly shown instead of fullscreen /// return .none to display as popover (ios 8.3+) public func adaptivePresentationStyle(for controller: UIPresentationController, traitCollection: UITraitCollection) -> UIModalPresentationStyle{ return .none } /// return .none to display as popover (ios 8.0 - 8.2) public func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle { return .none } // MARK: ViColorPickerDelegate public func didPickColor(sender: ViColorPickerModalViewController, color: String) { // set the color params if let colorParams = self.searchParams as? ViColorSearchParams { let oldColor = colorParams.color if oldColor != color { // reset the filter for filterItem in self.filterItems { filterItem.reset() } } colorParams.color = color sender.dismiss(animated: true, completion: nil) // update preview box and refresh data self.refreshData() // reset scroll self.resetScroll() } } /// since we show the Power by ViSenze image below the query product, it is not necessary to show again in the footer /// if query product is not available, then the Power by ViSenze image will appear in footer open override var footerSize : CGSize { return CGSize.zero } /// call ViSearch API and refresh the views open override func refreshData() { if( searchParams != nil && (searchParams is ViColorSearchParams) ) { if let searchParams = searchParams { // hide err message if any self.hideMsgView() self.setMetaQueryParamsForSearch() // check whether filter set to apply the filter self.setFilterQueryParamsForSearch() var client = self.searchClient if client == nil { client = ViSearch.sharedInstance.client } if let client = client { // set up user agent client.userAgent = ViWidgetVersion.USER_AGENT client.colorSearch( params: searchParams as! ViColorSearchParams, successHandler: { (data : ViResponseData?) -> Void in // check ViResponseData.hasError and ViResponseData.error for any errors return by ViSenze server if let data = data { if data.hasError { // clear products if there are errors self.products = [] DispatchQueue.main.async { self.displayDefaultErrMsg(searchType: ViSearchType.SEARCH_BY_COLOR , err: nil, apiErrors: data.error) } self.delegate?.searchFailed(sender: self, searchType: ViSearchType.SEARCH_BY_COLOR ,err: nil, apiErrors: data.error) } else { // display and refresh here self.reqId = data.reqId self.products = ViSchemaHelper.parseProducts(mapping: self.schemaMapping, data: data) if(self.products.count == 0 ){ DispatchQueue.main.async { self.displayNoResultsFoundMsg() } } self.delegate?.searchSuccess(sender: self, searchType: ViSearchType.SEARCH_BY_COLOR , reqId: data.reqId, products: self.products) } DispatchQueue.main.async { self.collectionView?.reloadData() } } }, failureHandler: { (err) -> Void in // clear products if there are errors self.products = [] DispatchQueue.main.async { self.displayDefaultErrMsg(searchType: ViSearchType.SEARCH_BY_COLOR , err: err, apiErrors: []) } self.delegate?.searchFailed(sender: self, searchType: ViSearchType.SEARCH_BY_COLOR , err: err, apiErrors: []) DispatchQueue.main.async { self.collectionView?.reloadData() } }) } else { print("\(type(of: self)).\(#function)[line:\(#line)] - error: client is not initialized.") } } } else { print("\(type(of: self)).\(#function)[line:\(#line)] - error: Search parameter must be ViColorSearchParams type and is not nil.") } } }
1c60cf8d7fe3ca7e3fb5f7080cb31018
38.533499
165
0.51406
false
false
false
false
chunzhiying/MeiPaiDemo
refs/heads/master
MeiPaiDemo/MeiPaiDemo/PhotosModel.swift
apache-2.0
1
// // PhotosModel.swift // MeiPaiDemo // // Created by 陈智颖 on 15/10/9. // Copyright © 2015年 YY. All rights reserved. // import UIKit import Foundation import Photos struct PhotosModelNotification { static let photoUpdated = "photoUpdated" } class PhotosModel: NSObject { static let shareInstance = PhotosModel() var assetAry = [PHAsset]() private var imageAry = [UIImage]() private var avAssetAry = [AVAsset]() private var targetSize: CGSize! // MARK: - Life Cycle private override init() { super.init() PHPhotoLibrary.sharedPhotoLibrary().registerChangeObserver(self) } deinit { PHPhotoLibrary.sharedPhotoLibrary().unregisterChangeObserver(self) } // 请求相册视频 func getVideoAssetFromPhotoAppWithTargetSize(targetSize: CGSize) { self.targetSize = targetSize assetAry.removeAll() let smartAlbum = PHAssetCollection.fetchAssetCollectionsWithType(.SmartAlbum, subtype: .SmartAlbumVideos, options: nil) guard smartAlbum.count > 0 else { return } let assetsFetchResult = PHAsset.fetchAssetsInAssetCollection(smartAlbum.firstObject as! PHAssetCollection , options: nil) for var i = 0; i < assetsFetchResult.count; i++ { let phAsset = assetsFetchResult.objectAtIndex(i) as! PHAsset assetAry += [phAsset] } } // 预览图 func getVideoImageByAsset(asset: PHAsset, complete: (UIImage) -> Void) { // 当targetSize = PHImageManagerMaximumSize,info中有视频的url,但是image为nil,targetSize为具体size时,有image,但是info中没有url PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: targetSize, contentMode:.AspectFit, options: nil) { imageOpt, infoOpt in guard let image = imageOpt else { return } complete(image) } } // 视频asset func getVideoAssetByAsset(asset: PHAsset, complete: (AVAsset) -> Void) { PHImageManager.defaultManager().requestAVAssetForVideo(asset, options: nil) { avAssetOpt, avAudioMixOpt, infoOpt in guard let avAsset = avAssetOpt else { return } complete(avAsset) } } // MARK: - Notification func postNotification() { NSNotificationCenter.defaultCenter().postNotificationName(PhotosModelNotification.photoUpdated, object: nil) } } extension PhotosModel: PHPhotoLibraryChangeObserver { func photoLibraryDidChange(changeInstance: PHChange) { dispatch_async(dispatch_get_main_queue()) { self.getVideoAssetFromPhotoAppWithTargetSize(self.targetSize) self.postNotification() } } }
e3fcd4eef498adc9cd36b1f91b0adb27
28.677419
152
0.652899
false
false
false
false
alirsamar/BiOS
refs/heads/master
ios-nd-pirate-fleet-2/Pirate Fleet/GridView.swift
mit
1
// // GridView.swift // Pirate Fleet // // Created by Jarrod Parkes on 8/14/15. // Copyright © 2015 Udacity, Inc. All rights reserved. // import UIKit // MARK: - GridViewDelegate protocol GridViewDelegate { func didTapCell(location: GridLocation) } // MARK: - GridView class GridView: UIView { // MARK: Properties var grid: [[GridCell]]! var delegate: GridViewDelegate? = nil var isInteractive = false { willSet { if newValue { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTapCell)) addGestureRecognizer(tapGesture) } else { if let gestureRecognizers = gestureRecognizers { for gestureRecognizer in gestureRecognizers { if gestureRecognizer is UITapGestureRecognizer { removeGestureRecognizer(gestureRecognizer) } } } } } } let cellBackgroundImage = UIImage(named: Settings.Images.Water) // MARK: Initializers required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) grid = [[GridCell]]() let center = self.center let sideLength = getSideLength() self.frame = CGRect(x: 0, y: 0, width: sideLength * CGFloat(Settings.DefaultGridSize.width), height: sideLength * CGFloat(Settings.DefaultGridSize.height)) self.center = center for x in 0..<Settings.DefaultGridSize.width { var cells = [GridCell]() for y in 0..<Settings.DefaultGridSize.height { let view = UIView() view.frame = CGRect(x: CGFloat(x) * sideLength, y: CGFloat(y) * sideLength, width: sideLength, height: sideLength) addBackgroundToView(view, backgroundImage: cellBackgroundImage) let gridCell = GridCell(location: GridLocation(x: x, y: y), view: view, containsObject: false, mine: nil, ship: nil, seamonster: nil) cells.append(gridCell) self.addSubview(view) } grid.append(cells) } } // MARK: Reset func reset() { for x in 0..<Settings.DefaultGridSize.width { for y in 0..<Settings.DefaultGridSize.height { for view in grid[x][y].view.subviews { view.removeFromSuperview() } grid[x][y].containsObject = false grid[x][y].mine = nil grid[x][y].seamonster = nil if let _ = grid[x][y].ship { grid[x][y].ship = nil } addBackgroundToView(grid[x][y].view, backgroundImage: cellBackgroundImage) } } } // MARK: Side Length private func getSideLength() -> CGFloat { let widthwiseSide = frame.size.width / CGFloat(Settings.DefaultGridSize.width) let lengthwiseSide = frame.size.height / CGFloat(Settings.DefaultGridSize.height) return (widthwiseSide > lengthwiseSide) ? lengthwiseSide : widthwiseSide } // MARK: Add Background To View private func addBackgroundToView(view: UIView, backgroundImage: UIImage?) { let imageView = UIImageView(frame: view.bounds) imageView.image = backgroundImage view.addSubview(imageView) view.sendSubviewToBack(imageView) } // MARK: UIView override func layoutSubviews() { super.layoutSubviews() guard let grid = grid else { return } let size = Settings.DefaultGridSize let sideLength = getSideLength() let center = self.center self.frame = CGRect(x: 0, y: 0, width: sideLength * CGFloat(size.width), height: sideLength * CGFloat(size.height)) self.center = center for x in 0..<size.width { for y in 0..<size.height { grid[x][y].view.frame = CGRect(x: CGFloat(x) * sideLength, y: CGFloat(y) * sideLength, width: sideLength, height: sideLength) for subview in grid[x][y].view.subviews { subview.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: grid[x][y].view.frame.size) } } } } } // MARK: - GridViewDelegate extension GridView { func didTapCell(tapGestureRecognizer: UITapGestureRecognizer) { guard let delegate = delegate else { return } guard isInteractive else { return } let tapLocation = tapGestureRecognizer.locationInView(self) let width = self.frame.size.width / CGFloat(grid.count) let height = self.frame.size.height / CGFloat(grid[0].count) let location = GridLocation(x: Int(tapLocation.x / width), y: Int(tapLocation.y / height)) delegate.didTapCell(location) } } // MARK: - Add Images to Grid extension GridView { func markImageAtLocation(location: GridLocation, image: String, hidden: Bool = false) { addImageAtLocation(location, image: image, hidden: hidden) } func markShipPieceAtLocation(location: GridLocation, orientation: ShipPieceOrientation, playerType: PlayerType, isWooden: Bool) { // if placing a computer piece, then hide it by default let hidden = (playerType == .Computer) ? true : false switch orientation { case .EndUp: if isWooden { addImageAtLocation(location, image: Settings.Images.WoodenShipHeadUpWithFlag, hidden: hidden) } else { addImageAtLocation(location, image: Settings.Images.ShipEndUp, hidden: hidden) } case .EndDown: if isWooden { addImageAtLocation(location, image: Settings.Images.WoodenShipHeadDown, hidden: hidden) } else { addImageAtLocation(location, image: Settings.Images.ShipEndDown, hidden: hidden) } case .EndLeft: if isWooden { addImageAtLocation(location, image: Settings.Images.WoodenShipHeadLeft, hidden: hidden) } else { addImageAtLocation(location, image: Settings.Images.ShipEndLeft, hidden: hidden) } case .EndRight: if isWooden { addImageAtLocation(location, image: Settings.Images.WoodenShipHeadRightWithFlag, hidden: hidden) } else { addImageAtLocation(location, image: Settings.Images.ShipEndRight, hidden: hidden) } case .BodyHorz: if isWooden { addImageAtLocation(location, image: Settings.Images.WoodenShipBodyHorz, hidden: hidden) } else { addImageAtLocation(location, image: Settings.Images.ShipBodyHorz, hidden: hidden) } case .BodyVert: if isWooden { addImageAtLocation(location, image: Settings.Images.WoodenShipBodyVert, hidden: hidden) } else { addImageAtLocation(location, image: Settings.Images.ShipBodyVert, hidden: hidden) } } } func revealLocations(locations: [GridLocation]) { for location in locations { for views in grid[location.x][location.y].view.subviews { views.hidden = false } } } private func addImageAtLocation(location: GridLocation, image: String, hidden: Bool = false) { let imageView = UIImageView(image: UIImage(named: image)) imageView.frame = CGRect(origin: CGPoint(x: 0, y: 0), size: self.grid[location.x][location.y].view.frame.size) imageView.hidden = hidden self.grid[location.x][location.y].view.addSubview(imageView) } }
39a051d62bebf86a03cee9343def0d2e
35.366516
163
0.582628
false
false
false
false
KaiCode2/ResearchKit
refs/heads/master
samples/ORKCatalog/ORKCatalog/TaskListRow.swift
bsd-3-clause
15
/* Copyright (c) 2015, Apple Inc. 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. */ import ResearchKit import AudioToolbox /** An enum that corresponds to a row displayed in a `TaskListViewController`. Each of the tasks is composed of one or more steps giving examples of the types of functionality supported by the ResearchKit framework. */ enum TaskListRow: Int, Printable { case ScaleQuestion = 0 case NumericQuestion case TimeOfDayQuestion case DateQuestion case DateTimeQuestion case TimeIntervalQuestion case TextQuestion case ValuePickerChoiceQuestion case TextChoiceQuestion case ImageChoiceQuestion case BooleanQuestion case TwoFingerTappingInterval case SpatialSpanMemory case Fitness case ShortWalk case Audio case ToneAudiometry case ReactionTime case TowerOfHanoi case PSAT case TimedWalk case HolePegTest case ImageCapture case Survey case Consent case Form /// Returns an array of all the task list row enum cases. static var allCases: [TaskListRow] { /* Create a generator that creates a `TaskListRow` at a specific index. When `TaskListRow`'s `rawValue` initializer returns `nil`, the generator will stop generating values. This will happen when the enum has no more cases represented by `caseIndex`. */ var caseIndex = 0 let caseGenerator = GeneratorOf { TaskListRow(rawValue: caseIndex++) } // Create a sequence that will consume the generator to create an array. let caseSequence = SequenceOf(caseGenerator) return Array(caseSequence) } // MARK: Printable var description: String { switch self { case .ScaleQuestion: return NSLocalizedString("Scale Question", comment: "") case .NumericQuestion: return NSLocalizedString("Numeric Question", comment: "") case .TimeOfDayQuestion: return NSLocalizedString("Time of Day Question", comment: "") case .DateQuestion: return NSLocalizedString("Date Question", comment: "") case .DateTimeQuestion: return NSLocalizedString("Date and Time Question", comment: "") case .TimeIntervalQuestion: return NSLocalizedString("Time Interval Question", comment: "") case .TextQuestion: return NSLocalizedString("Text Question", comment: "") case .ValuePickerChoiceQuestion: return NSLocalizedString("Value Picker Choice Question", comment: "") case .TextChoiceQuestion: return NSLocalizedString("Text Choice Question", comment: "") case .ImageChoiceQuestion: return NSLocalizedString("Image Choice Question", comment: "") case .BooleanQuestion: return NSLocalizedString("Boolean Question", comment: "") case .TwoFingerTappingInterval: return NSLocalizedString("Two Finger Tapping Interval Active Task", comment: "") case .SpatialSpanMemory: return NSLocalizedString("Spatial Span Memory Active Task", comment: "") case .Fitness: return NSLocalizedString("Fitness Check Active Task", comment: "") case .ShortWalk: return NSLocalizedString("Short Walk Active Task", comment: "") case .Audio: return NSLocalizedString("Audio Active Task", comment: "") case .ToneAudiometry: return NSLocalizedString("Tone Audiometry Active Task", comment: "") case .ReactionTime: return NSLocalizedString("Reaction Time Active Task", comment: "") case .TowerOfHanoi: return NSLocalizedString("Tower of Hanoi Active Task", comment: "") case .PSAT: return NSLocalizedString("PSAT Active Task", comment: "") case .TimedWalk: return NSLocalizedString("Timed Walk", comment: "") case .HolePegTest: return NSLocalizedString("Hole Peg Test Task", comment: "") case .ImageCapture: return NSLocalizedString("Image Capture Task", comment: "") case .Survey: return NSLocalizedString("Simple Survey", comment: "") case .Consent: return NSLocalizedString("Consent", comment: "") case .Form: return NSLocalizedString("Form", comment: "") } } // MARK: Types /** Every step and task in the ResearchKit framework has to have an identifier. Within a task, the step identifiers should be unique. Here we use an enum to ensure that the identifiers are kept unique. Since the enum has a raw underlying type of a `String`, the compiler can determine the uniqueness of the case values at compile time. In a real application, the identifiers for your tasks and steps might come from a database, or in a smaller application, might have some human-readable meaning. */ private enum Identifier: String { // Task with examples of questions with sliding scales. case ScaleQuestionTask = "ScaleQuestionTask" case DiscreteScaleQuestionStep = "DiscreteScaleQuestionStep" case ContinuousScaleQuestionStep = "ContinuousScaleQuestionStep" case DiscreteVerticalScaleQuestionStep = "DiscreteVerticalScaleQuestionStep" case ContinuousVerticalScaleQuestionStep = "ContinuousVerticalScaleQuestionStep" // Task with examples of numeric questions. case NumericQuestionTask = "NumericQuestionTask" case NumericQuestionStep = "NumericQuestionStep" case NumericNoUnitQuestionStep = "NumericNoUnitQuestionStep" // Task with an example of time of day entry. case TimeOfDayQuestionTask = "TimeOfDayQuestionTask" case TimeOfDayQuestionStep = "TimeOfDayQuestionStep" // Task with an example of date entry. case DateQuestionTask = "DateQuestionTask" case DateQuestionStep = "DateQuestionStep" // Task with an example of date and time entry. case DateTimeQuestionTask = "DateTimeQuestionTask" case DateTimeQuestionStep = "DateTimeQuestionStep" // Task with an example of time interval entry. case TimeIntervalQuestionTask = "TimeIntervalQuestionTask" case TimeIntervalQuestionStep = "TimeIntervalQuestionStep" // Task with an example of free text entry. case TextQuestionTask = "TextQuestionTask" case TextQuestionStep = "TextQuestionStep" // Task with a value picker. case ValuePickerChoiceQuestionTask = "ValuePickerChoiceQuestionTask" case ValuePickerChoiceQuestionStep = "ValuePickerChoiceQuestionStep" // Task with an example of a multiple choice question. case TextChoiceQuestionTask = "TextChoiceQuestionTask" case TextChoiceQuestionStep = "TextChoiceQuestionStep" // Task with an image choice question. case ImageChoiceQuestionTask = "ImageChoiceQuestionTask" case ImageChoiceQuestionStep = "ImageChoiceQuestionStep" // Survey example with a Boolean question. case BooleanQuestionTask = "BooleanQuestionTask" case BooleanQuestionStep = "BooleanQuestionStep" // Active tasks. case TwoFingerTappingIntervalTask = "TwoFingerTappingIntervalTask" case SpatialSpanMemoryTask = "SpatialSpanMemoryTask" case FitnessTask = "FitnessTask" case ShortWalkTask = "ShortWalkTask" case AudioTask = "AudioTask" case ToneAudiometryTask = "ToneAudiometry" case ReactionTime = "ReactionTime" case TowerOfHanoi = "TowerOfHanoi" case PSATTask = "PSATTask" case TimedWalkTask = "TimedWalkTask" case HolePegTestTask = "HolePegTestTask" // Image capture task specific identifiers. case ImageCaptureTask = "ImageCaptureTask" case ImageCaptureStep = "ImageCaptureStep" // Survey task specific identifiers. case SurveyTask = "SurveyTask" case IntroStep = "IntroStep" case QuestionStep = "QuestionStep" case SummaryStep = "SummaryStep" // Consent task specific identifiers. case ConsentTask = "ConsentTask" case VisualConsentStep = "VisualConsentStep" case ConsentSharingStep = "ConsentSharingStep" case ConsentReviewStep = "ConsentReviewStep" case ConsentDocumentParticipantSignature = "ConsentDocumentParticipantSignature" case ConsentDocumentInvestigatorSignature = "ConsentDocumentInvestigatorSignature" // Task with a form, where multiple items appear on one page. case FormTask = "FormTask" case FormStep = "FormStep" case FormItem01 = "FormItem01" case FormItem02 = "FormItem02" } // MARK: Properties /// Returns a new `ORKTask` that the `TaskListRow` enumeration represents. var representedTask: ORKTask { switch self { case .ScaleQuestion: return scaleQuestionTask case .NumericQuestion: return numericQuestionTask case .TimeOfDayQuestion: return timeOfDayQuestionTask case .DateQuestion: return dateQuestionTask case .DateTimeQuestion: return dateTimeQuestionTask case .TimeIntervalQuestion: return timeIntervalQuestionTask case .TextQuestion: return textQuestionTask case .ValuePickerChoiceQuestion: return valuePickerChoiceQuestionTask case .TextChoiceQuestion: return textChoiceQuestionTask case .ImageChoiceQuestion: return imageChoiceQuestionTask case .BooleanQuestion: return booleanQuestionTask case .TwoFingerTappingInterval: return twoFingerTappingIntervalTask case .SpatialSpanMemory: return spatialSpanMemoryTask case .Fitness: return fitnessTask case .ShortWalk: return shortWalkTask case .Audio: return audioTask case .ToneAudiometry: return toneAudiometryTask case .ReactionTime: return reactionTimeTask case .TowerOfHanoi: return towerOfHanoiTask case .PSAT: return PSATTask case .TimedWalk: return TimedWalkTask case .HolePegTest: return holePegTestTask case .ImageCapture: return imageCaptureTask case .Survey: return surveyTask case .Consent: return consentTask case .Form: return formTask } } // MARK: Task Creation Convenience /// This task presents two options for questions displaying a scale control. private var scaleQuestionTask: ORKTask { var steps = [ORKStep]() // The first step is a scale control with 10 discrete ticks. let step1AnswerFormat = ORKAnswerFormat.scaleAnswerFormatWithMaximumValue(10, minimumValue: 1, defaultValue: NSIntegerMax, step: 1, vertical: false, maximumValueDescription: exampleHighValueText, minimumValueDescription: exampleLowValueText) let questionStep1 = ORKQuestionStep(identifier: Identifier.DiscreteScaleQuestionStep.rawValue, title: exampleQuestionText, answer: step1AnswerFormat) questionStep1.text = exampleDetailText steps += [questionStep1] // The second step is a scale control that allows continuous movement with a percent formatter. let step2AnswerFormat = ORKAnswerFormat.continuousScaleAnswerFormatWithMaximumValue(1.0, minimumValue: 0.0, defaultValue: 99.0, maximumFractionDigits: 0, vertical: false, maximumValueDescription: nil, minimumValueDescription: nil) step2AnswerFormat.numberStyle = .Percent let questionStep2 = ORKQuestionStep(identifier: Identifier.ContinuousScaleQuestionStep.rawValue, title: exampleQuestionText, answer: step2AnswerFormat) questionStep2.text = exampleDetailText steps += [questionStep2] // The third step is a vertical scale control with 10 discrete ticks. let step3AnswerFormat = ORKAnswerFormat.scaleAnswerFormatWithMaximumValue(10, minimumValue: 1, defaultValue: NSIntegerMax, step: 1, vertical: true, maximumValueDescription: nil, minimumValueDescription: nil) let questionStep3 = ORKQuestionStep(identifier: Identifier.DiscreteVerticalScaleQuestionStep.rawValue, title: exampleQuestionText, answer: step3AnswerFormat) questionStep3.text = exampleDetailText steps += [questionStep3] // The fourth step is a vertical scale control that allows continuous movement. let step4AnswerFormat = ORKAnswerFormat.continuousScaleAnswerFormatWithMaximumValue(5.0, minimumValue: 1.0, defaultValue: 99.0, maximumFractionDigits: 2, vertical: true, maximumValueDescription: exampleHighValueText, minimumValueDescription: exampleLowValueText) let questionStep4 = ORKQuestionStep(identifier: Identifier.ContinuousVerticalScaleQuestionStep.rawValue, title: exampleQuestionText, answer: step4AnswerFormat) questionStep4.text = exampleDetailText steps += [questionStep4] return ORKOrderedTask(identifier: Identifier.ScaleQuestionTask.rawValue, steps: steps) } /** This task demonstrates use of numeric questions with and without units. Note that the unit is just a string, prompting the user to enter the value in the expected unit. The unit string propagates into the result object. */ private var numericQuestionTask: ORKTask { var steps = [ORKStep]() // This answer format will display a unit in-line with the numeric entry field. let localizedQuestionStep1AnswerFormatUnit = NSLocalizedString("Your unit", comment: "") let questionStep1AnswerFormat = ORKAnswerFormat.decimalAnswerFormatWithUnit(localizedQuestionStep1AnswerFormatUnit) let questionStep1 = ORKQuestionStep(identifier: Identifier.NumericQuestionStep.rawValue, title: exampleQuestionText, answer: questionStep1AnswerFormat) questionStep1.text = exampleDetailText questionStep1.placeholder = NSLocalizedString("Your placeholder.", comment: "") steps += [questionStep1] // This answer format is similar to the previous one, but this time without displaying a unit. let questionStep2 = ORKQuestionStep(identifier: Identifier.NumericNoUnitQuestionStep.rawValue, title: exampleQuestionText, answer: ORKAnswerFormat.decimalAnswerFormatWithUnit(nil)) questionStep2.text = exampleDetailText questionStep2.placeholder = NSLocalizedString("Placeholder without unit.", comment: "") steps += [questionStep2] return ORKOrderedTask(identifier: Identifier.NumericQuestionTask.rawValue, steps: steps) } /// This task demonstrates a question asking for a time of day. private var timeOfDayQuestionTask: ORKTask { /* Because we don't specify a default, the picker will default to the time the step is presented. For questions like "What time do you have breakfast?", it would make sense to set the default on the answer format. */ let answerFormat = ORKAnswerFormat.timeOfDayAnswerFormat() let questionStep = ORKQuestionStep(identifier: Identifier.TimeOfDayQuestionStep.rawValue, title: exampleQuestionText, answer: answerFormat) questionStep.text = exampleDetailText return ORKOrderedTask(identifier: Identifier.TimeOfDayQuestionTask.rawValue, steps: [questionStep]) } /// This task demonstrates a question which asks for a date. private var dateQuestionTask: ORKTask { /* The date answer format can also support minimum and maximum limits, a specific default value, and overriding the calendar to use. */ let answerFormat = ORKAnswerFormat.dateAnswerFormat() let step = ORKQuestionStep(identifier: Identifier.DateQuestionStep.rawValue, title: exampleQuestionText, answer: answerFormat) step.text = exampleDetailText return ORKOrderedTask(identifier: Identifier.DateQuestionTask.rawValue, steps: [step]) } /// This task demonstrates a question asking for a date and time of an event. private var dateTimeQuestionTask: ORKTask { /* This uses the default calendar. Use a more detailed constructor to set minimum / maximum limits. */ let answerFormat = ORKAnswerFormat.dateTimeAnswerFormat() let step = ORKQuestionStep(identifier: Identifier.DateTimeQuestionStep.rawValue, title: exampleQuestionText, answer: answerFormat) step.text = exampleDetailText return ORKOrderedTask(identifier: Identifier.DateTimeQuestionTask.rawValue, steps: [step]) } /** This task demonstrates requesting a time interval. For example, this might be a suitable answer format for a question like "How long is your morning commute?" */ private var timeIntervalQuestionTask: ORKTask { /* The time interval answer format is constrained to entering a time less than 24 hours and in steps of minutes. For times that don't fit these restrictions, use another mode of data entry. */ let answerFormat = ORKAnswerFormat.timeIntervalAnswerFormat() let step = ORKQuestionStep(identifier: Identifier.TimeIntervalQuestionStep.rawValue, title: exampleQuestionText, answer: answerFormat) step.text = exampleDetailText return ORKOrderedTask(identifier: Identifier.TimeIntervalQuestionTask.rawValue, steps: [step]) } /** This task demonstrates asking for text entry. Both single and multi-line text entry are supported, with appropriate parameters to the text answer format. */ private var textQuestionTask: ORKTask { let answerFormat = ORKAnswerFormat.textAnswerFormat() let step = ORKQuestionStep(identifier: Identifier.TextQuestionStep.rawValue, title: exampleQuestionText, answer: ORKAnswerFormat.textAnswerFormat()) step.text = exampleDetailText return ORKOrderedTask(identifier: Identifier.TextQuestionTask.rawValue, steps: [step]) } /** This task demonstrates a survey question using a value picker wheel. Compare with the `textChoiceQuestionTask` and `imageChoiceQuestionTask` which can serve a similar purpose. */ private var valuePickerChoiceQuestionTask: ORKTask { let textChoiceOneText = NSLocalizedString("Choice 1", comment: "") let textChoiceTwoText = NSLocalizedString("Choice 2", comment: "") let textChoiceThreeText = NSLocalizedString("Choice 3", comment: "") // The text to display can be separate from the value coded for each choice: let textChoices = [ ORKTextChoice(text: textChoiceOneText, value: "choice_1"), ORKTextChoice(text: textChoiceTwoText, value: "choice_2"), ORKTextChoice(text: textChoiceThreeText, value: "choice_3") ] let answerFormat = ORKAnswerFormat.valuePickerAnswerFormatWithTextChoices(textChoices) let questionStep = ORKQuestionStep(identifier: Identifier.ValuePickerChoiceQuestionStep.rawValue, title: exampleQuestionText, answer: answerFormat) questionStep.text = exampleDetailText return ORKOrderedTask(identifier: Identifier.ValuePickerChoiceQuestionTask.rawValue, steps: [questionStep]) } /** This task demonstrates a survey question for picking from a list of text choices. In this case, the text choices are presented in a table view (compare with the `valuePickerQuestionTask`). */ private var textChoiceQuestionTask: ORKTask { let textChoiceOneText = NSLocalizedString("Choice 1", comment: "") let textChoiceTwoText = NSLocalizedString("Choice 2", comment: "") let textChoiceThreeText = NSLocalizedString("Choice 3", comment: "") // The text to display can be separate from the value coded for each choice: let textChoices = [ ORKTextChoice(text: textChoiceOneText, value: "choice_1"), ORKTextChoice(text: textChoiceTwoText, value: "choice_2"), ORKTextChoice(text: textChoiceThreeText, value: "choice_3") ] let answerFormat = ORKAnswerFormat.choiceAnswerFormatWithStyle(.SingleChoice, textChoices: textChoices) let questionStep = ORKQuestionStep(identifier: Identifier.TextChoiceQuestionStep.rawValue, title: exampleQuestionText, answer: answerFormat) questionStep.text = exampleDetailText return ORKOrderedTask(identifier: Identifier.TextChoiceQuestionTask.rawValue, steps: [questionStep]) } /** This task demonstrates a survey question involving picking from a series of image choices. A more realistic applciation of this type of question might be to use a range of icons for faces ranging from happy to sad. */ private var imageChoiceQuestionTask: ORKTask { let roundShapeImage = UIImage(named: "round_shape")! let roundShapeText = NSLocalizedString("Round Shape", comment: "") let squareShapeImage = UIImage(named: "square_shape")! let squareShapeText = NSLocalizedString("Square Shape", comment: "") let imageChoces = [ ORKImageChoice(normalImage: roundShapeImage, selectedImage: nil, text: roundShapeText, value: roundShapeText), ORKImageChoice(normalImage: squareShapeImage, selectedImage: nil, text: squareShapeText, value: squareShapeText) ] let answerFormat = ORKAnswerFormat.choiceAnswerFormatWithImageChoices(imageChoces) let questionStep = ORKQuestionStep(identifier: Identifier.ImageChoiceQuestionStep.rawValue, title: exampleQuestionText, answer: answerFormat) questionStep.text = exampleDetailText return ORKOrderedTask(identifier: Identifier.ImageChoiceQuestionTask.rawValue, steps: [questionStep]) } /// This task presents just a single "Yes" / "No" question. private var booleanQuestionTask: ORKTask { let answerFormat = ORKBooleanAnswerFormat() // We attach an answer format to a question step to specify what controls the user sees. let questionStep = ORKQuestionStep(identifier: Identifier.BooleanQuestionStep.rawValue, title: exampleQuestionText, answer: answerFormat) // The detail text is shown in a small font below the title. questionStep.text = exampleDetailText return ORKOrderedTask(identifier: Identifier.BooleanQuestionTask.rawValue, steps: [questionStep]) } /// This task presents the Two Finger Tapping pre-defined active task. private var twoFingerTappingIntervalTask: ORKTask { return ORKOrderedTask.twoFingerTappingIntervalTaskWithIdentifier(Identifier.TwoFingerTappingIntervalTask.rawValue, intendedUseDescription: exampleDescription, duration: 20, options: nil) } /// This task presents the Spatial Span Memory pre-defined active task. private var spatialSpanMemoryTask: ORKTask { return ORKOrderedTask.spatialSpanMemoryTaskWithIdentifier(Identifier.SpatialSpanMemoryTask.rawValue, intendedUseDescription: exampleDescription, initialSpan: 3, minimumSpan: 2, maximumSpan: 15, playSpeed: 1.0, maxTests: 5, maxConsecutiveFailures: 3, customTargetImage: nil, customTargetPluralName: nil, requireReversal: false, options: nil) } /** This task presents the Fitness pre-defined active task. For this example, short walking and rest durations of 20 seconds each are used, whereas more realistic durations might be several minutes each. */ private var fitnessTask: ORKTask { return ORKOrderedTask.fitnessCheckTaskWithIdentifier(Identifier.FitnessTask.rawValue, intendedUseDescription: exampleDescription, walkDuration: 20, restDuration: 20, options: nil) } /// This task presents the Gait and Balance pre-defined active task. private var shortWalkTask: ORKTask { return ORKOrderedTask.shortWalkTaskWithIdentifier(Identifier.ShortWalkTask.rawValue, intendedUseDescription: exampleDescription, numberOfStepsPerLeg: 20, restDuration: 20, options: nil) } /// This task presents the Audio pre-defined active task. private var audioTask: ORKTask { return ORKOrderedTask.audioTaskWithIdentifier(Identifier.AudioTask.rawValue, intendedUseDescription: exampleDescription, speechInstruction: exampleSpeechInstruction, shortSpeechInstruction: exampleSpeechInstruction, duration: 20, recordingSettings: nil, options: nil) } private var reactionTimeTask: ORKTask { return ORKOrderedTask.reactionTimeTaskWithIdentifier(Identifier.ReactionTime.rawValue, intendedUseDescription: exampleDescription, maximumStimulusInterval: 10, minimumStimulusInterval: 4, thresholdAcceleration: 0.5, numberOfAttempts: 3, timeout: 3, successSound: exampleSuccessSound, timeoutSound: 0, failureSound: UInt32(kSystemSoundID_Vibrate), options: nil) } private var towerOfHanoiTask: ORKTask { return ORKOrderedTask.towerOfHanoiTaskWithIdentifier(Identifier.TowerOfHanoi.rawValue, intendedUseDescription: exampleDescription, numberOfDisks: 5, options: nil) } /// This task presents the PSAT pre-defined active task. private var PSATTask: ORKTask { return ORKOrderedTask.PSATTaskWithIdentifier(Identifier.PSATTask.rawValue, intendedUseDescription: exampleDescription, presentationMode: (.Auditory | .Visual), interStimulusInterval: 3.0, stimulusDuration: 1.0, seriesLength: 60, options: nil) } /// This task presents the Timed Walk pre-defined active task. private var timedWalkTask: ORKTask { return ORKOrderedTask.timedWalkTaskWithIdentifier(String(Identifier.TimedWalkTask), intendedUseDescription: exampleDescription, distanceInMeters: 100.0, timeLimit: 180.0, includeAssistiveDeviceForm: true, options: []) } /// This task presents the Hole Peg Test pre-defined active task. private var holePegTestTask: ORKTask { return ORKNavigableOrderedTask.holePegTestTaskWithIdentifier(Identifier.HolePegTestTask.rawValue, intendedUseDescription: exampleDescription, dominantHand: .Right, numberOfPegs: 9, threshold: 0.2, rotated: false, timeLimit: 300, options: nil) } private var exampleSuccessSound: UInt32 { var successSoundPath: CFURLRef! = NSURL(fileURLWithPath: "///System/Library/Audio/UISounds/Modern/sms_alert_complete.caf") as CFURLRef! var soundID: SystemSoundID = 0 AudioServicesCreateSystemSoundID(successSoundPath, &soundID) return soundID } /// This task presents the Tone Audiometry pre-defined active task. private var toneAudiometryTask: ORKTask { return ORKOrderedTask.toneAudiometryTaskWithIdentifier(Identifier.ToneAudiometryTask.rawValue, intendedUseDescription: exampleDescription, speechInstruction: nil, shortSpeechInstruction: nil, toneDuration: 20, options: nil) } /// This task presents the image capture step in an ordered task. private var imageCaptureTask: ORKTask { var steps = [ORKStep]() // Create the intro step. let instructionStep = ORKInstructionStep(identifier: Identifier.IntroStep.rawValue) instructionStep.title = NSLocalizedString("Sample Survey", comment: "") instructionStep.text = exampleDescription instructionStep.image = UIImage(named: "hand_solid")!.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) steps += [instructionStep] let imageCaptureStep = ORKImageCaptureStep(identifier: Identifier.ImageCaptureStep.rawValue) imageCaptureStep.optional = false imageCaptureStep.accessibilityInstructions = NSLocalizedString("Your instructions for capturing the image", comment: "") imageCaptureStep.accessibilityHint = NSLocalizedString("Captures the image visible in the preview", comment: "") imageCaptureStep.templateImage = UIImage(named: "hand_outline_big")! imageCaptureStep.templateImageInsets = UIEdgeInsets(top: 0.05, left: 0.05, bottom: 0.05, right: 0.05) steps += [imageCaptureStep] return ORKOrderedTask(identifier: Identifier.ImageCaptureTask.rawValue, steps: steps) } /** A task demonstrating how the ResearchKit framework can be used to present a simple survey with an introduction, a question, and a conclusion. */ private var surveyTask: ORKTask { var steps = [ORKStep]() // Create the intro step. let instructionStep = ORKInstructionStep(identifier: Identifier.IntroStep.rawValue) instructionStep.title = NSLocalizedString("Sample Survey", comment: "") instructionStep.text = exampleDescription steps += [instructionStep] // Add a question step. let questionStepAnswerFormat = ORKBooleanAnswerFormat() let questionStepTitle = NSLocalizedString("Would you like to subscribe to our newsletter?", comment: "") let questionStep = ORKQuestionStep(identifier: Identifier.QuestionStep.rawValue, title: questionStepTitle, answer: questionStepAnswerFormat) steps += [questionStep] // Add a summary step. let summaryStep = ORKInstructionStep(identifier: Identifier.SummaryStep.rawValue) summaryStep.title = NSLocalizedString("Thanks", comment: "") summaryStep.text = NSLocalizedString("Thank you for participating in this sample survey.", comment: "") steps += [summaryStep] return ORKOrderedTask(identifier: Identifier.SurveyTask.rawValue, steps: steps) } /// A task demonstrating how the ResearchKit framework can be used to obtain informed consent. private var consentTask: ORKTask { var steps = [ORKStep]() /* Informed consent starts by presenting an animated sequence conveying the main points of your consent document. */ let visualConsentStep = ORKVisualConsentStep(identifier: Identifier.VisualConsentStep.rawValue, document: consentDocument) steps += [visualConsentStep] let investigatorShortDescription = NSLocalizedString("Institution", comment: "") let investigatorLongDescription = NSLocalizedString("Institution and its partners", comment: "") let localizedLearnMoreHTMLContent = NSLocalizedString("Your sharing learn more content here.", comment: "") /* If you want to share the data you collect with other researchers for use in other studies beyond this one, it is best practice to get explicit permission from the participant. Use the consent sharing step for this. */ let sharingConsentStep = ORKConsentSharingStep(identifier: Identifier.ConsentSharingStep.rawValue, investigatorShortDescription: investigatorShortDescription, investigatorLongDescription: investigatorLongDescription, localizedLearnMoreHTMLContent: localizedLearnMoreHTMLContent) steps += [sharingConsentStep] /* After the visual presentation, the consent review step displays your consent document and can obtain a signature from the participant. The first signature in the document is the participant's signature. This effectively tells the consent review step which signatory is reviewing the document. */ let signature = consentDocument.signatures!.first as! ORKConsentSignature let reviewConsentStep = ORKConsentReviewStep(identifier: Identifier.ConsentReviewStep.rawValue, signature: signature, inDocument: consentDocument) // In a real application, you would supply your own localized text. reviewConsentStep.text = loremIpsumText reviewConsentStep.reasonForConsent = loremIpsumText steps += [reviewConsentStep] return ORKOrderedTask(identifier: Identifier.ConsentTask.rawValue, steps: steps) } /** This task demonstrates a form step, in which multiple items are presented in a single scrollable form. This might be used for entering multi-value data, like taking a blood pressure reading with separate systolic and diastolic values. */ private var formTask: ORKTask { let step = ORKFormStep(identifier: Identifier.FormTask.rawValue, title: exampleQuestionText, text: exampleDetailText) // A first field, for entering an integer. let formItem01Text = NSLocalizedString("Field01", comment: "") let formItem01 = ORKFormItem(identifier: Identifier.FormItem01.rawValue, text: formItem01Text, answerFormat: ORKAnswerFormat.integerAnswerFormatWithUnit(nil)) formItem01.placeholder = NSLocalizedString("Your placeholder here", comment: "") // A second field, for entering a time interval. let formItem02Text = NSLocalizedString("Field02", comment: "") let formItem02 = ORKFormItem(identifier: Identifier.FormItem02.rawValue, text: formItem02Text, answerFormat: ORKTimeIntervalAnswerFormat()) formItem02.placeholder = NSLocalizedString("Your placeholder here", comment: "") step.formItems = [formItem01, formItem02] return ORKOrderedTask(identifier: Identifier.FormTask.rawValue, steps: [step]) } // MARK: Consent Document Creation Convenience /** A consent document provides the content for the visual consent and consent review steps. This helper sets up a consent document with some dummy content. You should populate your consent document to suit your study. */ private var consentDocument: ORKConsentDocument { let consentDocument = ORKConsentDocument() /* This is the title of the document, displayed both for review and in the generated PDF. */ consentDocument.title = NSLocalizedString("Example Consent", comment: "") // This is the title of the signature page in the generated document. consentDocument.signaturePageTitle = NSLocalizedString("Consent", comment: "") /* This is the line shown on the signature page of the generated document, just above the signatures. */ consentDocument.signaturePageContent = NSLocalizedString("I agree to participate in this research study.", comment: "") /* Add the participant signature, which will be filled in during the consent review process. This signature initially does not have a signature image or a participant name; these are collected during the consent review step. */ let participantSignatureTitle = NSLocalizedString("Participant", comment: "") let participantSignature = ORKConsentSignature(forPersonWithTitle: participantSignatureTitle, dateFormatString: nil, identifier: Identifier.ConsentDocumentParticipantSignature.rawValue) consentDocument.addSignature(participantSignature) /* Add the investigator signature. This is pre-populated with the investigator's signature image and name, and the date of their signature. If you need to specify the date as now, you could generate a date string with code here. This signature is only used for the generated PDF. */ let signatureImage = UIImage(named: "signature")! let investigatorSignatureTitle = NSLocalizedString("Investigator", comment: "") let investigatorSignatureGivenName = NSLocalizedString("Jonny", comment: "") let investigatorSignatureFamilyName = NSLocalizedString("Appleseed", comment: "") let investigatorSignatureDateString = "3/10/15" let investigatorSignature = ORKConsentSignature(forPersonWithTitle: investigatorSignatureTitle, dateFormatString: nil, identifier: Identifier.ConsentDocumentInvestigatorSignature.rawValue, givenName: investigatorSignatureGivenName, familyName: investigatorSignatureFamilyName, signatureImage: signatureImage, dateString: investigatorSignatureDateString) consentDocument.addSignature(investigatorSignature) /* This is the HTML content for the "Learn More" page for each consent section. In a real consent, this would be your content, and you would have different content for each section. If your content is just text, you can use the `content` property instead of the `htmlContent` property of `ORKConsentSection`. */ let htmlContentString = "<ul><li>Lorem</li><li>ipsum</li><li>dolor</li></ul><p>\(loremIpsumLongText)</p><p>\(loremIpsumMediumText)</p>" /* These are all the consent section types that have pre-defined animations and images. We use them in this specific order, so we see the available animated transitions. */ let consentSectionTypes: [ORKConsentSectionType] = [ .Overview, .DataGathering, .Privacy, .DataUse, .TimeCommitment, .StudySurvey, .StudyTasks, .Withdrawing ] /* For each consent section type in `consentSectionTypes`, create an `ORKConsentSection` that represents it. In a real app, you would set specific content for each section. */ var consentSections: [ORKConsentSection] = consentSectionTypes.map { contentSectionType in let consentSection = ORKConsentSection(type: contentSectionType) consentSection.summary = self.loremIpsumShortText if contentSectionType == .Overview { consentSection.htmlContent = htmlContentString } else { consentSection.content = self.loremIpsumLongText } return consentSection } /* This is an example of a section that is only in the review document or only in the generated PDF, and is not displayed in `ORKVisualConsentStep`. */ let consentSection = ORKConsentSection(type: .OnlyInDocument) consentSection.summary = NSLocalizedString(".OnlyInDocument Scene Summary", comment: "") consentSection.title = NSLocalizedString(".OnlyInDocument Scene", comment: "") consentSection.content = loremIpsumLongText consentSections += [consentSection] // Set the sections on the document after they've been created. consentDocument.sections = consentSections return consentDocument } // MARK: `ORKTask` Reused Text Convenience private var exampleDescription: String { return NSLocalizedString("Your description goes here.", comment: "") } private var exampleSpeechInstruction: String { return NSLocalizedString("Your more specific voice instruction goes here. For example, say 'Aaaah'.", comment: "") } private var exampleQuestionText: String { return NSLocalizedString("Your question goes here.", comment: "") } private var exampleHighValueText: String { return NSLocalizedString("High Value", comment: "") } private var exampleLowValueText: String { return NSLocalizedString("Low Value", comment: "") } private var exampleDetailText: String { return NSLocalizedString("Additional text can go here.", comment: "") } private var loremIpsumText: String { return "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." } private var loremIpsumShortText: String { return "Lorem ipsum dolor sit amet, consectetur adipiscing elit." } private var loremIpsumMediumText: String { return "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam adhuc, meo fortasse vitio, quid ego quaeram non perspicis. Plane idem, inquit, et maxima quidem, qua fieri nulla maior potest. Quonam, inquit, modo?" } private var loremIpsumLongText: String { return "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam adhuc, meo fortasse vitio, quid ego quaeram non perspicis. Plane idem, inquit, et maxima quidem, qua fieri nulla maior potest. Quonam, inquit, modo? An potest, inquit ille, quicquam esse suavius quam nihil dolere? Cave putes quicquam esse verius. Quonam, inquit, modo?" } }
5db25ae612fcdb75e1dba8934a710a0b
46.804777
368
0.652207
false
false
false
false
guidomb/Portal
refs/heads/master
Portal/View/UIKit/UIKitRenderer.swift
mit
1
// // UIKitRenderer.swift // PortalView // // Created by Guido Marucci Blas on 2/14/17. // Copyright © 2017 Guido Marucci Blas. All rights reserved. // import UIKit public struct UIKitComponentRenderer< MessageType, RouteType, CustomComponentRendererType: UIKitCustomComponentRenderer >: Renderer where CustomComponentRendererType.MessageType == MessageType, CustomComponentRendererType.RouteType == RouteType { public typealias CustomComponentRendererFactory = () -> CustomComponentRendererType public typealias ActionType = Action<RouteType, MessageType> typealias TableView = PortalTableView<MessageType, RouteType, CustomComponentRendererType> typealias CollectionView = PortalCollectionView<MessageType, RouteType, CustomComponentRendererType> typealias CarouselView = PortalCarouselView<MessageType, RouteType, CustomComponentRendererType> public var isDebugModeEnabled = false public var debugConfiguration = RendererDebugConfiguration() fileprivate let layoutEngine: LayoutEngine fileprivate let rendererFactory: CustomComponentRendererFactory public init( layoutEngine: LayoutEngine = YogaLayoutEngine(), rendererFactory: @escaping CustomComponentRendererFactory) { self.rendererFactory = rendererFactory self.layoutEngine = layoutEngine } public func render(component: Component<ActionType>, into containerView: UIView) -> Mailbox<ActionType> { apply(changeSet: component.fullChangeSet, to: containerView) return containerView.getMailbox() } public func apply(changeSet: ComponentChangeSet<ActionType>, to containerView: UIView) { let rootView = getOrCreateRootView(from: containerView) let renderResult = render(changeSet: changeSet, into: rootView) if rootView !== renderResult.view { containerView.addSubview(renderResult.view) renderResult.mailbox?.forward(to: containerView.getMailbox()) } layoutEngine.executeLayout(for: containerView) renderResult.afterLayout?() if isShowViewFrame { renderResult.view.safeTraverse { $0.addDebugFrame() } } } } extension UIKitComponentRenderer { var isShowViewChangeAnimation: Bool { return isDebugModeEnabled && debugConfiguration.showViewChangeAnimation } var isShowViewFrame: Bool { return isDebugModeEnabled && debugConfiguration.showViewFrame } // swiftlint:disable cyclomatic_complexity function_body_length fileprivate func render(changeSet: ComponentChangeSet<ActionType>, into view: UIView?) -> Render<ActionType> { // We need to remove any gesture recognizers that could have been added // if the view was wrapped with a touchable component in the previous // render cycle. // // We need to do this here to avoid having gesture recognizers that are // no longer valid in case this view is no longer wrapped // with a touchable component but can be reused to render the current // change set. // // We need to differentiate which are the gesture recognizers managed // by Portal because if we remove all gesture recognizer, things like // scrolling detection on table and collection views won't work. view?.removeAllManagedGestureRecognizers() switch changeSet { case .button(let buttonChangeSet): let button = castOrRelease(view: view, to: UIButton.self) return button.apply(changeSet: buttonChangeSet, layoutEngine: layoutEngine) case .label(let labelChangeSet): let label = castOrRelease(view: view, to: UILabel.self) return label.apply(changeSet: labelChangeSet, layoutEngine: layoutEngine) case .mapView(let mapViewChangeSet): let mapView = castOrRelease(view: view, to: PortalMapView.self) return mapView.apply(changeSet: mapViewChangeSet, layoutEngine: layoutEngine) case .imageView(let imageViewChangeSet): let imageView = castOrRelease(view: view, to: UIImageView.self) return imageView.apply(changeSet: imageViewChangeSet, layoutEngine: layoutEngine) case .container(let containerChangeSet): // We need to make sure that view's type is UIView and not // any of it's subclasses because container components // cannot be renderer inside a UIButton for example. if let containerView = view, type(of: containerView) == UIView.self { return apply(changeSet: containerChangeSet, to: containerView) } else { let containerView = UIView() containerView.managedByPortal = true return apply(changeSet: containerChangeSet, to: containerView) } case .table(let tableChangeSet): let table = castOrRelease(view: view, to: TableView.self) { TableView(renderer: self) } return table.apply(changeSet: tableChangeSet, layoutEngine: layoutEngine) case .collection(let collectionChangeSet): let collection = castOrRelease(view: view, to: CollectionView.self) { CollectionView(renderer: self) } return collection.apply(changeSet: collectionChangeSet, layoutEngine: layoutEngine) case .carousel(let carouselChangeSet): let carousel = castOrRelease(view: view, to: CarouselView.self) { CarouselView(renderer: self) } return carousel.apply(changeSet: carouselChangeSet, layoutEngine: layoutEngine) case .touchable(let touchableChangeSet): return apply(changeSet: touchableChangeSet, to: view) case .segmented(let segmentedChangeSet): let segmented = castOrRelease(view: view, to: UISegmentedControl.self) return segmented.apply(changeSet: segmentedChangeSet, layoutEngine: layoutEngine) case .progress(let progressChangeSet): let progress = castOrRelease(view: view, to: UIProgressView.self) return progress.apply(changeSet: progressChangeSet, layoutEngine: layoutEngine) case .textField(let textFieldChangeSet): let textField = castOrRelease(view: view, to: UITextField.self) return textField.apply(changeSet: textFieldChangeSet, layoutEngine: layoutEngine) case .custom(let customComponentChangeSet): return apply(changeSet: customComponentChangeSet, to: view ?? UIView()) case .spinner(let spinnerChangeSet): let spinner = castOrRelease(view: view, to: UIActivityIndicatorView.self) return spinner.apply(changeSet: spinnerChangeSet, layoutEngine: layoutEngine) case .textView(let textViewChangeSet): let textView = castOrRelease(view: view, to: UITextView.self) return textView.apply(changeSet: textViewChangeSet, layoutEngine: layoutEngine) case .toggle(let toggleChangeSet): let toggle = castOrRelease(view: view, to: UISwitch.self) return toggle.apply(changeSet: toggleChangeSet, layoutEngine: layoutEngine) } } // swiftlint:enable cyclomatic_complexity function_body_length fileprivate func apply(changeSet: TouchableChangeSet<ActionType>, to view: UIView?) -> Render<ActionType> { let result = render(changeSet: changeSet.child, into: view) switch changeSet.gesture { case .change(to: .tap(let message)): if result.view is UIImageView { result.view.isUserInteractionEnabled = true } let mailbox: Mailbox<ActionType> = result.view.getMailbox() let dispatcher = MessageDispatcher(mailbox: mailbox, message: message) result.view.register(dispatcher: dispatcher) let recognizer = UITapGestureRecognizer(target: dispatcher, action: dispatcher.selector) result.view.addManagedGestureRecognizer(recognizer) case .noChange: break } return result } fileprivate func apply(changeSet: CustomComponentChangeSet, to containerView: UIView) -> Render<ActionType> { containerView.managedByPortal = true layoutEngine.apply(changeSet: changeSet.layout, to: containerView) containerView.apply(changeSet: changeSet.baseStyleSheet) let mailbox: Mailbox<ActionType> = containerView.getMailbox() return Render(view: containerView, mailbox: mailbox) { let renderer = self.rendererFactory() renderer.apply(changeSet: changeSet, inside: containerView, dispatcher: mailbox.dispatch) } } fileprivate func apply(changeSet: ContainerChangeSet<ActionType>, to view: UIView) -> Render<ActionType> { var afterLayoutTasks = [AfterLayoutTask]() afterLayoutTasks.reserveCapacity(changeSet.childrenCount) let reuseSubviews = view.subviews.count == changeSet.childrenCount let subviews: [UIView?] if reuseSubviews { subviews = view.subviews } else { view.subviews.forEach { $0.removeFromSuperview() } subviews = Array(repeating: .none, count: changeSet.childrenCount) } let mailbox: Mailbox<ActionType> = view.getMailbox() for (index, (subview, childChangeSet)) in zip(subviews, changeSet.children).enumerated() { let result = render(changeSet: childChangeSet, into: subview) if !reuseSubviews || result.view !== subview { result.view.managedByPortal = true result.mailbox?.forward(to: mailbox) if reuseSubviews { view.insertSubview(result.view, at: index) subview?.removeFromSuperview() } else { view.addSubview(result.view) } } if isShowViewChangeAnimation && !changeSet.isEmpty { result.view.addChangeDebugAnimation() } if let afterLayoutTask = result.afterLayout { afterLayoutTasks.append(afterLayoutTask) } } view.apply(changeSet: changeSet.baseStyleSheet) layoutEngine.apply(changeSet: changeSet.layout, to: view) return Render(view: view, mailbox: mailbox) { afterLayoutTasks.forEach { $0() } } } fileprivate func castOrRelease<SpecificView: UIView>( view: UIView?, to viewType: SpecificView.Type, viewFactory: (() -> SpecificView)? = .none) -> SpecificView { if view != nil && view is SpecificView { return view as! SpecificView //swiftlint:disable:this force_cast } else { view?.removeFromSuperview() let newView = viewFactory?() ?? SpecificView() return newView } } fileprivate func getOrCreateRootView(from containerView: UIView) -> UIView { let view: UIView if let subview = containerView.subviews.first { view = subview } else { view = UIView() containerView.addSubview(view) let mailbox: Mailbox<ActionType> = view.getMailbox() mailbox.forward(to: containerView.getMailbox()) } return view } } internal typealias AfterLayoutTask = () -> Void internal struct Render<MessageType> { let view: UIView let mailbox: Mailbox<MessageType>? let afterLayout: AfterLayoutTask? init(view: UIView, mailbox: Mailbox<MessageType>? = .none, executeAfterLayout afterLayout: AfterLayoutTask? = .none) { self.view = view self.afterLayout = afterLayout self.mailbox = mailbox } }
83606637c9870c0f6ff79a5452a13a65
41.288194
118
0.647262
false
false
false
false
lexchou/swallow
refs/heads/master
stdlib/reference-archives/swiftCore-1.2-602.0.49.6.swift
bsd-3-clause
1
//shim @objc protocol _SwiftNSZone { } struct _SwiftNSFastEnumerationState {} struct _SwiftNSRange {} protocol _DisabledRangeIndex_ { } protocol _OptionalNilComparisonType { } struct _UnitTestArray<T> { } struct _UnitTestArrayBuffer<T> { } struct _ContiguousArrayBuffer<T> { } //swiftCore /// The empty tuple type. /// /// This is the default return type of functions for which no explicit /// return type is specified. typealias Void = () infix operator & { associativity left precedence 150 } infix operator >= { associativity none precedence 130 } infix operator ~= { associativity none precedence 130 } infix operator !== { associativity none precedence 130 } infix operator < { associativity none precedence 130 } infix operator | { associativity left precedence 140 } infix operator >> { associativity none precedence 160 } infix operator ~> { associativity left precedence 255 } infix operator > { associativity none precedence 130 } infix operator != { associativity none precedence 130 } infix operator <= { associativity none precedence 130 } infix operator |= { associativity right precedence 90 assignment } infix operator >>= { associativity right precedence 90 assignment } infix operator << { associativity none precedence 160 } infix operator %= { associativity right precedence 90 assignment } infix operator || { associativity left precedence 110 } infix operator <<= { associativity right precedence 90 assignment } infix operator / { associativity left precedence 150 } infix operator - { associativity left precedence 140 } infix operator + { associativity left precedence 140 } infix operator * { associativity left precedence 150 } infix operator *= { associativity right precedence 90 assignment } infix operator % { associativity left precedence 150 } infix operator += { associativity right precedence 90 assignment } infix operator -= { associativity right precedence 90 assignment } infix operator ... { associativity none precedence 135 } infix operator /= { associativity right precedence 90 assignment } infix operator && { associativity left precedence 120 } infix operator &* { associativity left precedence 150 } infix operator &+ { associativity left precedence 140 } infix operator &- { associativity left precedence 140 } infix operator === { associativity none precedence 130 } infix operator ..< { associativity none precedence 135 } infix operator == { associativity none precedence 130 } infix operator ^= { associativity right precedence 90 assignment } infix operator ?? { associativity right precedence 131 } infix operator ^ { associativity left precedence 140 } infix operator &= { associativity right precedence 90 assignment } prefix operator ! { } prefix operator -- { } prefix operator ~ { } prefix operator + { } prefix operator - { } prefix operator ++ { } postfix operator -- { } postfix operator ++ { } prefix func !(a: Bool) -> Bool /// Return the result of inverting `a`\ 's logic value prefix func !<T : BooleanType>(a: T) -> Bool func !=(lhs: UInt16, rhs: UInt16) -> Bool func !=(lhs: Int8, rhs: Int8) -> Bool func !=(lhs: Int16, rhs: Int16) -> Bool func !=(lhs: UInt32, rhs: UInt32) -> Bool func !=(lhs: Int32, rhs: Int32) -> Bool func !=(lhs: UInt64, rhs: UInt64) -> Bool func !=(lhs: Int64, rhs: Int64) -> Bool func !=(lhs: UInt, rhs: UInt) -> Bool /// Returns true if the arrays do not contain the same elements. func !=<T : Equatable>(lhs: ArraySlice<T>, rhs: ArraySlice<T>) -> Bool func !=<T : Equatable>(lhs: T, rhs: T) -> Bool func !=<T>(lhs: _OptionalNilComparisonType, rhs: T?) -> Bool func !=<T>(lhs: T?, rhs: _OptionalNilComparisonType) -> Bool func !=<T : Equatable>(lhs: T?, rhs: T?) -> Bool /// Returns true if the arrays do not contain the same elements. func !=<T : Equatable>(lhs: ContiguousArray<T>, rhs: ContiguousArray<T>) -> Bool func !=<Key : Equatable, Value : Equatable>(lhs: [Key : Value], rhs: [Key : Value]) -> Bool func !=(lhs: Float80, rhs: Float80) -> Bool func !=(lhs: Double, rhs: Double) -> Bool func !=(lhs: Float, rhs: Float) -> Bool /// Returns true if the arrays do not contain the same elements. func !=<T : Equatable>(lhs: [T], rhs: [T]) -> Bool func !=(lhs: Int, rhs: Int) -> Bool /// Returns true if the arrays do not contain the same elements. func !=<T : Equatable>(lhs: _UnitTestArray<T>, rhs: _UnitTestArray<T>) -> Bool func !=(lhs: UInt8, rhs: UInt8) -> Bool func !==(lhs: AnyObject?, rhs: AnyObject?) -> Bool func %(lhs: UInt8, rhs: UInt8) -> UInt8 func %(lhs: Int8, rhs: Int8) -> Int8 func %(lhs: UInt16, rhs: UInt16) -> UInt16 func %(lhs: Int16, rhs: Int16) -> Int16 func %(lhs: UInt32, rhs: UInt32) -> UInt32 func %(lhs: Int32, rhs: Int32) -> Int32 func %(lhs: UInt64, rhs: UInt64) -> UInt64 func %(lhs: Int64, rhs: Int64) -> Int64 func %(lhs: Int, rhs: Int) -> Int func %(lhs: Float, rhs: Float) -> Float func %(lhs: Double, rhs: Double) -> Double func %(lhs: Float80, rhs: Float80) -> Float80 /// Divide `lhs` and `rhs`, returning the remainder and trapping in case of /// arithmetic overflow (except in -Ounchecked builds). func %<T : _IntegerArithmeticType>(lhs: T, rhs: T) -> T func %(lhs: UInt, rhs: UInt) -> UInt func %=(inout lhs: Float, rhs: Float) /// remainder `lhs` and `rhs` and store the result in `lhs`, trapping in /// case of arithmetic overflow (except in -Ounchecked builds). func %=<T : _IntegerArithmeticType>(inout lhs: T, rhs: T) func %=(inout lhs: Float80, rhs: Float80) func %=(inout lhs: Double, rhs: Double) func &(lhs: UInt8, rhs: UInt8) -> UInt8 func &(lhs: Int8, rhs: Int8) -> Int8 func &(lhs: UInt16, rhs: UInt16) -> UInt16 func &(lhs: Int16, rhs: Int16) -> Int16 func &(lhs: UInt32, rhs: UInt32) -> UInt32 func &(lhs: Int32, rhs: Int32) -> Int32 func &(lhs: UInt64, rhs: UInt64) -> UInt64 func &(lhs: Int64, rhs: Int64) -> Int64 func &(lhs: UInt, rhs: UInt) -> UInt func &(lhs: Int, rhs: Int) -> Int func &<T : _RawOptionSetType>(a: T, b: T) -> T func &&<T : BooleanType>(lhs: T, rhs: @autoclosure () -> Bool) -> Bool /// If `lhs` is `false`, return it. Otherwise, evaluate `rhs` and /// return its `boolValue`. @inline(__always) func &&<T : BooleanType, U : BooleanType>(lhs: T, rhs: @autoclosure () -> U) -> Bool /// multiply `lhs` and `rhs`, silently discarding any overflow. func &*<T : _IntegerArithmeticType>(lhs: T, rhs: T) -> T /// add `lhs` and `rhs`, silently discarding any overflow. func &+<T : _IntegerArithmeticType>(lhs: T, rhs: T) -> T /// subtract `lhs` and `rhs`, silently discarding any overflow. func &-<T : _IntegerArithmeticType>(lhs: T, rhs: T) -> T func &=(inout lhs: Int16, rhs: Int16) func &=<T : BitwiseOperationsType>(inout lhs: T, rhs: T) func &=(inout lhs: Int, rhs: Int) func &=(inout lhs: UInt, rhs: UInt) func &=(inout lhs: Int64, rhs: Int64) func &=(inout lhs: UInt64, rhs: UInt64) func &=(inout lhs: Int32, rhs: Int32) func &=(inout lhs: UInt32, rhs: UInt32) func &=(inout lhs: UInt16, rhs: UInt16) func &=(inout lhs: Int8, rhs: Int8) func &=(inout lhs: UInt8, rhs: UInt8) func *(lhs: UInt32, rhs: UInt32) -> UInt32 func *(lhs: UInt8, rhs: UInt8) -> UInt8 func *(lhs: Int8, rhs: Int8) -> Int8 func *(lhs: UInt16, rhs: UInt16) -> UInt16 /// Multiply `lhs` and `rhs`, returning a result and trapping in case of /// arithmetic overflow (except in -Ounchecked builds). func *<T : _IntegerArithmeticType>(lhs: T, rhs: T) -> T func *(lhs: Float80, rhs: Float80) -> Float80 func *(lhs: Int16, rhs: Int16) -> Int16 func *(lhs: Double, rhs: Double) -> Double func *(lhs: Float, rhs: Float) -> Float func *(lhs: Int, rhs: Int) -> Int func *(lhs: UInt, rhs: UInt) -> UInt func *(lhs: Int64, rhs: Int64) -> Int64 func *(lhs: UInt64, rhs: UInt64) -> UInt64 func *(lhs: Int32, rhs: Int32) -> Int32 func *=(inout lhs: UInt8, rhs: UInt8) func *=(inout lhs: Int8, rhs: Int8) func *=(inout lhs: UInt16, rhs: UInt16) func *=(inout lhs: Int16, rhs: Int16) func *=(inout lhs: UInt32, rhs: UInt32) func *=(inout lhs: Int32, rhs: Int32) func *=(inout lhs: UInt64, rhs: UInt64) func *=(inout lhs: Int64, rhs: Int64) func *=(inout lhs: UInt, rhs: UInt) func *=(inout lhs: Int, rhs: Int) func *=(inout lhs: Float, rhs: Float) func *=(inout lhs: Double, rhs: Double) func *=(inout lhs: Float80, rhs: Float80) /// multiply `lhs` and `rhs` and store the result in `lhs`, trapping in /// case of arithmetic overflow (except in -Ounchecked builds). func *=<T : _IntegerArithmeticType>(inout lhs: T, rhs: T) prefix func +<T : _SignedNumberType>(x: T) -> T func +<C : _ExtensibleCollectionType, S : SequenceType>(lhs: C, rhs: S) -> C func +<C : _ExtensibleCollectionType, S : SequenceType>(lhs: S, rhs: C) -> C func +<C : _ExtensibleCollectionType, S : CollectionType>(lhs: C, rhs: S) -> C func +<EC1 : _ExtensibleCollectionType, EC2 : _ExtensibleCollectionType>(lhs: EC1, rhs: EC2) -> EC1 func +<T : Strideable>(lhs: T, rhs: T.Stride) -> T func +<T : Strideable>(lhs: T.Stride, rhs: T) -> T func +<T : _UnsignedIntegerType>(lhs: T, rhs: T._DisallowMixedSignArithmetic) -> T func +<T : _UnsignedIntegerType>(lhs: T._DisallowMixedSignArithmetic, rhs: T) -> T func +(lhs: String, rhs: String) -> String func +<T>(lhs: UnsafeMutablePointer<T>, rhs: Int) -> UnsafeMutablePointer<T> func +<T>(lhs: Int, rhs: UnsafeMutablePointer<T>) -> UnsafeMutablePointer<T> func +<T>(lhs: UnsafePointer<T>, rhs: Int) -> UnsafePointer<T> func +<T>(lhs: Int, rhs: UnsafePointer<T>) -> UnsafePointer<T> func +(lhs: UInt8, rhs: UInt8) -> UInt8 func +(lhs: Int8, rhs: Int8) -> Int8 func +(lhs: UInt16, rhs: UInt16) -> UInt16 func +(lhs: Int16, rhs: Int16) -> Int16 func +(lhs: UInt32, rhs: UInt32) -> UInt32 func +(lhs: Int32, rhs: Int32) -> Int32 func +(lhs: UInt64, rhs: UInt64) -> UInt64 func +(lhs: Int64, rhs: Int64) -> Int64 func +(lhs: UInt, rhs: UInt) -> UInt func +(lhs: Int, rhs: Int) -> Int prefix func +(x: Float) -> Float /// Add `lhs` and `rhs`, returning a result and trapping in case of /// arithmetic overflow (except in -Ounchecked builds). func +<T : _IntegerArithmeticType>(lhs: T, rhs: T) -> T func +(lhs: Float80, rhs: Float80) -> Float80 prefix func +(x: Float80) -> Float80 func +(lhs: Double, rhs: Double) -> Double prefix func +(x: Double) -> Double func +(lhs: Float, rhs: Float) -> Float prefix func ++(inout x: UInt8) -> UInt8 postfix func ++(inout x: UInt8) -> UInt8 prefix func ++(inout x: Int8) -> Int8 prefix func ++(inout x: UInt64) -> UInt64 postfix func ++(inout x: UInt64) -> UInt64 prefix func ++(inout x: Int64) -> Int64 postfix func ++(inout x: Int64) -> Int64 prefix func ++(inout x: UInt) -> UInt postfix func ++(inout x: UInt) -> UInt prefix func ++(inout x: Int) -> Int postfix func ++(inout x: Int) -> Int prefix func ++(inout rhs: Float) -> Float postfix func ++(inout lhs: Float) -> Float prefix func ++(inout rhs: Double) -> Double postfix func ++(inout lhs: Double) -> Double prefix func ++(inout rhs: Float80) -> Float80 postfix func ++(inout lhs: Float80) -> Float80 prefix func ++<T : _Incrementable>(inout x: T) -> T postfix func ++<T : _Incrementable>(inout x: T) -> T postfix func ++(inout x: Int8) -> Int8 prefix func ++(inout x: UInt16) -> UInt16 postfix func ++(inout x: UInt16) -> UInt16 prefix func ++(inout x: Int16) -> Int16 postfix func ++(inout x: Int16) -> Int16 prefix func ++(inout x: UInt32) -> UInt32 postfix func ++(inout x: UInt32) -> UInt32 prefix func ++(inout x: Int32) -> Int32 postfix func ++(inout x: Int32) -> Int32 func +=(inout lhs: UInt8, rhs: UInt8) /// Extend `lhs` with the elements of `rhs` func +=<T, C : CollectionType>(inout lhs: [T], rhs: C) func +=<T>(inout lhs: UnsafePointer<T>, rhs: Int) func +=<T>(inout lhs: UnsafeMutablePointer<T>, rhs: Int) /// Append rhs to lhs func +=<T>(inout lhs: _UnitTestArrayBuffer<T>, rhs: T) /// Append the elements of rhs to lhs func +=<T, C : CollectionType>(inout lhs: _UnitTestArrayBuffer<T>, rhs: C) func +=(inout lhs: String, rhs: String) func +=<T : _UnsignedIntegerType>(inout lhs: T, rhs: T._DisallowMixedSignArithmetic) func +=<T : Strideable>(inout lhs: T, rhs: T.Stride) /// add `lhs` and `rhs` and store the result in `lhs`, trapping in /// case of arithmetic overflow (except in -Ounchecked builds). func +=<T : _IntegerArithmeticType>(inout lhs: T, rhs: T) func +=(inout lhs: Float80, rhs: Float80) func +=(inout lhs: Double, rhs: Double) func +=(inout lhs: Float, rhs: Float) func +=(inout lhs: Int, rhs: Int) func +=(inout lhs: UInt, rhs: UInt) func +=(inout lhs: Int64, rhs: Int64) func +=(inout lhs: UInt64, rhs: UInt64) func +=(inout lhs: Int32, rhs: Int32) func +=(inout lhs: UInt32, rhs: UInt32) func +=(inout lhs: Int16, rhs: Int16) func +=(inout lhs: UInt16, rhs: UInt16) func +=(inout lhs: Int8, rhs: Int8) /// Append the elements of rhs to lhs func +=<T, C : CollectionType>(inout lhs: _ContiguousArrayBuffer<T>, rhs: C) /// Extend `lhs` with the elements of `rhs` func +=<T, S : SequenceType>(inout lhs: ContiguousArray<T>, rhs: S) /// Extend `lhs` with the elements of `rhs` func +=<T, C : CollectionType>(inout lhs: ContiguousArray<T>, rhs: C) /// Extend `lhs` with the elements of `rhs` func +=<T, S : SequenceType>(inout lhs: ArraySlice<T>, rhs: S) /// Extend `lhs` with the elements of `rhs` func +=<T, C : CollectionType>(inout lhs: ArraySlice<T>, rhs: C) /// Extend `lhs` with the elements of `rhs` func +=<T, S : SequenceType>(inout lhs: [T], rhs: S) /// Extend `lhs` with the elements of `rhs` func +=<T, C : CollectionType>(inout lhs: _UnitTestArray<T>, rhs: C) /// Extend `lhs` with the elements of `rhs` func +=<T, S : SequenceType>(inout lhs: _UnitTestArray<T>, rhs: S) func -(lhs: UInt16, rhs: UInt16) -> UInt16 func -<T : _UnsignedIntegerType>(lhs: T, rhs: T) -> T._DisallowMixedSignArithmetic func -<T>(lhs: UnsafeMutablePointer<T>, rhs: Int) -> UnsafeMutablePointer<T> func -<T : _UnsignedIntegerType>(lhs: T, rhs: T._DisallowMixedSignArithmetic) -> T func -<T : Strideable>(lhs: T, rhs: T) -> T.Stride func -<T : Strideable>(lhs: T, rhs: T.Stride) -> T prefix func -<T : _SignedNumberType>(x: T) -> T /// Subtract `lhs` and `rhs`, returning a result and trapping in case of /// arithmetic overflow (except in -Ounchecked builds). func -<T : _IntegerArithmeticType>(lhs: T, rhs: T) -> T func -(lhs: Float80, rhs: Float80) -> Float80 prefix func -(x: Float80) -> Float80 func -(lhs: Double, rhs: Double) -> Double prefix func -(x: Double) -> Double func -(lhs: Float, rhs: Float) -> Float prefix func -(x: Float) -> Float func -(lhs: Int, rhs: Int) -> Int func -(lhs: UInt, rhs: UInt) -> UInt func -(lhs: Int64, rhs: Int64) -> Int64 func -(lhs: UInt64, rhs: UInt64) -> UInt64 func -(lhs: Int32, rhs: Int32) -> Int32 func -(lhs: UInt32, rhs: UInt32) -> UInt32 func -(lhs: Int16, rhs: Int16) -> Int16 func -(lhs: UInt8, rhs: UInt8) -> UInt8 func -(lhs: Int8, rhs: Int8) -> Int8 func -<T>(lhs: UnsafeMutablePointer<T>, rhs: UnsafeMutablePointer<T>) -> Int func -<T>(lhs: UnsafePointer<T>, rhs: Int) -> UnsafePointer<T> func -<T>(lhs: UnsafePointer<T>, rhs: UnsafePointer<T>) -> Int prefix func --(inout x: Int64) -> Int64 postfix func --(inout x: UInt) -> UInt prefix func --(inout x: UInt8) -> UInt8 postfix func --(inout x: UInt8) -> UInt8 prefix func --(inout x: Int8) -> Int8 postfix func --(inout x: Int8) -> Int8 prefix func --(inout x: UInt16) -> UInt16 postfix func --(inout x: UInt16) -> UInt16 prefix func --(inout x: Int16) -> Int16 postfix func --(inout x: Int16) -> Int16 prefix func --(inout x: UInt32) -> UInt32 postfix func --(inout x: UInt32) -> UInt32 prefix func --(inout x: Int32) -> Int32 postfix func --<T : _BidirectionalIndexType>(inout x: T) -> T prefix func --<T : _BidirectionalIndexType>(inout x: T) -> T postfix func --(inout lhs: Float80) -> Float80 prefix func --(inout rhs: Float80) -> Float80 postfix func --(inout lhs: Double) -> Double prefix func --(inout rhs: Double) -> Double postfix func --(inout lhs: Float) -> Float prefix func --(inout rhs: Float) -> Float postfix func --(inout x: Int) -> Int prefix func --(inout x: Int) -> Int postfix func --(inout x: Int32) -> Int32 prefix func --(inout x: UInt) -> UInt postfix func --(inout x: Int64) -> Int64 prefix func --(inout x: UInt64) -> UInt64 postfix func --(inout x: UInt64) -> UInt64 func -=(inout lhs: UInt, rhs: UInt) func -=(inout lhs: Int64, rhs: Int64) func -=<T : Strideable>(inout lhs: T, rhs: T.Stride) func -=<T : _UnsignedIntegerType>(inout lhs: T, rhs: T._DisallowMixedSignArithmetic) func -=<T>(inout lhs: UnsafeMutablePointer<T>, rhs: Int) func -=<T>(inout lhs: UnsafePointer<T>, rhs: Int) func -=(inout lhs: UInt8, rhs: UInt8) func -=(inout lhs: Int8, rhs: Int8) func -=(inout lhs: UInt16, rhs: UInt16) func -=(inout lhs: Int16, rhs: Int16) func -=(inout lhs: UInt32, rhs: UInt32) func -=(inout lhs: Int32, rhs: Int32) func -=(inout lhs: UInt64, rhs: UInt64) /// subtract `lhs` and `rhs` and store the result in `lhs`, trapping in /// case of arithmetic overflow (except in -Ounchecked builds). func -=<T : _IntegerArithmeticType>(inout lhs: T, rhs: T) func -=(inout lhs: Float80, rhs: Float80) func -=(inout lhs: Double, rhs: Double) func -=(inout lhs: Float, rhs: Float) func -=(inout lhs: Int, rhs: Int) /// Returns a closed interval from `start` through `end` func ...<T : Comparable>(start: T, end: T) -> ClosedInterval<T> /// Forms a closed range that contains both `minimum` and `maximum`. func ...<Pos : ForwardIndexType>(minimum: Pos, maximum: Pos) -> Range<Pos> /// Forms a closed range that contains both `start` and `end`. /// Requres: `start <= end` func ...<Pos : ForwardIndexType where Pos : Comparable>(start: Pos, end: Pos) -> Range<Pos> /// Forms a half-open range that contains `minimum`, but not /// `maximum`. func ..<<Pos : ForwardIndexType>(minimum: Pos, maximum: Pos) -> Range<Pos> /// Returns a half-open interval from `start` to `end` func ..<<T : Comparable>(start: T, end: T) -> HalfOpenInterval<T> /// Forms a half-open range that contains `start`, but not /// `end`. Requires: `start <= end` func ..<<Pos : ForwardIndexType where Pos : Comparable>(start: Pos, end: Pos) -> Range<Pos> func /(lhs: UInt16, rhs: UInt16) -> UInt16 func /(lhs: Int8, rhs: Int8) -> Int8 func /(lhs: UInt8, rhs: UInt8) -> UInt8 func /(lhs: Int16, rhs: Int16) -> Int16 func /(lhs: UInt32, rhs: UInt32) -> UInt32 func /(lhs: Int32, rhs: Int32) -> Int32 func /(lhs: UInt64, rhs: UInt64) -> UInt64 func /(lhs: Int64, rhs: Int64) -> Int64 func /(lhs: UInt, rhs: UInt) -> UInt func /(lhs: Float, rhs: Float) -> Float func /(lhs: Double, rhs: Double) -> Double func /(lhs: Float80, rhs: Float80) -> Float80 /// Divide `lhs` and `rhs`, returning a result and trapping in case of /// arithmetic overflow (except in -Ounchecked builds). func /<T : _IntegerArithmeticType>(lhs: T, rhs: T) -> T func /(lhs: Int, rhs: Int) -> Int func /=(inout lhs: Float, rhs: Float) func /=(inout lhs: Double, rhs: Double) func /=(inout lhs: Float80, rhs: Float80) /// divide `lhs` and `rhs` and store the result in `lhs`, trapping in /// case of arithmetic overflow (except in -Ounchecked builds). func /=<T : _IntegerArithmeticType>(inout lhs: T, rhs: T) func <(lhs: UInt8, rhs: UInt8) -> Bool func <(lhs: Int8, rhs: Int8) -> Bool func <(lhs: UInt16, rhs: UInt16) -> Bool func <(lhs: Int16, rhs: Int16) -> Bool func <(lhs: UInt32, rhs: UInt32) -> Bool func <(lhs: Int32, rhs: Int32) -> Bool func <(lhs: UInt64, rhs: UInt64) -> Bool func <(lhs: Character, rhs: Character) -> Bool func <(lhs: UInt, rhs: UInt) -> Bool func <(lhs: Int, rhs: Int) -> Bool func <(lhs: Float, rhs: Float) -> Bool func <(lhs: Double, rhs: Double) -> Bool func <(lhs: Float80, rhs: Float80) -> Bool func <<T : Hashable>(lhs: SetIndex<T>, rhs: SetIndex<T>) -> Bool func <<Key : Hashable, Value>(lhs: DictionaryIndex<Key, Value>, rhs: DictionaryIndex<Key, Value>) -> Bool func <<T : _Comparable>(lhs: T?, rhs: T?) -> Bool func <(lhs: ObjectIdentifier, rhs: ObjectIdentifier) -> Bool /// Compare two Strideables func <<T : _Strideable>(x: T, y: T) -> Bool func <(lhs: String, rhs: String) -> Bool func <(lhs: String.Index, rhs: String.Index) -> Bool func <(lhs: String.UTF16View.Index, rhs: String.UTF16View.Index) -> Bool func <(lhs: String.UnicodeScalarView.Index, rhs: String.UnicodeScalarView.Index) -> Bool func <(lhs: UnicodeScalar, rhs: UnicodeScalar) -> Bool func <<T>(lhs: UnsafeMutablePointer<T>, rhs: UnsafeMutablePointer<T>) -> Bool func <<T>(lhs: UnsafePointer<T>, rhs: UnsafePointer<T>) -> Bool func <(lhs: Bit, rhs: Bit) -> Bool func <(lhs: Int64, rhs: Int64) -> Bool func <<(lhs: Int8, rhs: Int8) -> Int8 func <<(lhs: UInt16, rhs: UInt16) -> UInt16 func <<(lhs: Int16, rhs: Int16) -> Int16 func <<(lhs: UInt32, rhs: UInt32) -> UInt32 func <<(lhs: Int32, rhs: Int32) -> Int32 func <<(lhs: UInt64, rhs: UInt64) -> UInt64 func <<(lhs: Int64, rhs: Int64) -> Int64 func <<(lhs: UInt, rhs: UInt) -> UInt func <<(lhs: Int, rhs: Int) -> Int func <<(lhs: UInt8, rhs: UInt8) -> UInt8 func <<=(inout lhs: Int64, rhs: Int64) func <<=(inout lhs: Int, rhs: Int) func <<=(inout lhs: UInt, rhs: UInt) func <<=(inout lhs: UInt64, rhs: UInt64) func <<=(inout lhs: Int32, rhs: Int32) func <<=(inout lhs: UInt32, rhs: UInt32) func <<=(inout lhs: Int16, rhs: Int16) func <<=(inout lhs: UInt16, rhs: UInt16) func <<=(inout lhs: Int8, rhs: Int8) func <<=(inout lhs: UInt8, rhs: UInt8) func <=(lhs: Int8, rhs: Int8) -> Bool func <=(lhs: UInt8, rhs: UInt8) -> Bool func <=(lhs: UInt16, rhs: UInt16) -> Bool func <=(lhs: Int16, rhs: Int16) -> Bool func <=(lhs: UInt32, rhs: UInt32) -> Bool func <=(lhs: Int32, rhs: Int32) -> Bool func <=(lhs: UInt64, rhs: UInt64) -> Bool func <=(lhs: Int64, rhs: Int64) -> Bool func <=(lhs: UInt, rhs: UInt) -> Bool func <=(lhs: Int, rhs: Int) -> Bool func <=(lhs: Float, rhs: Float) -> Bool func <=(lhs: Double, rhs: Double) -> Bool func <=(lhs: Float80, rhs: Float80) -> Bool func <=<T : _Comparable>(lhs: T?, rhs: T?) -> Bool func <=<T : _Comparable>(lhs: T, rhs: T) -> Bool func ==(lhs: Bit, rhs: Bit) -> Bool func ==(lhs: String.UnicodeScalarView.Index, rhs: String.UnicodeScalarView.Index) -> Bool func ==(lhs: String.UTF8View.Index, rhs: String.UTF8View.Index) -> Bool func ==(lhs: String.UTF16View.Index, rhs: String.UTF16View.Index) -> Bool func ==(lhs: String.Index, rhs: String.Index) -> Bool func ==(lhs: String, rhs: String) -> Bool func ==<T : _Strideable>(x: T, y: T) -> Bool func ==<I>(lhs: ReverseRandomAccessIndex<I>, rhs: ReverseRandomAccessIndex<I>) -> Bool func ==<I>(lhs: ReverseBidirectionalIndex<I>, rhs: ReverseBidirectionalIndex<I>) -> Bool func ==(lhs: Bool, rhs: Bool) -> Bool func ==(x: ObjectIdentifier, y: ObjectIdentifier) -> Bool func ==<T>(lhs: Range<T>, rhs: Range<T>) -> Bool func ==<T>(lhs: AutoreleasingUnsafeMutablePointer<T>, rhs: AutoreleasingUnsafeMutablePointer<T>) -> Bool /// Returns true if these arrays contain the same elements. func ==<T : Equatable>(lhs: _UnitTestArray<T>, rhs: _UnitTestArray<T>) -> Bool func ==<T>(lhs: _OptionalNilComparisonType, rhs: T?) -> Bool func ==<T>(lhs: T?, rhs: _OptionalNilComparisonType) -> Bool func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool func ==<Value, Element>(lhs: ManagedBufferPointer<Value, Element>, rhs: ManagedBufferPointer<Value, Element>) -> Bool func ==(lhs: COpaquePointer, rhs: COpaquePointer) -> Bool func ==<T>(lhs: CFunctionPointer<T>, rhs: CFunctionPointer<T>) -> Bool func ==(lhs: UnicodeScalar, rhs: UnicodeScalar) -> Bool /// Returns true if these arrays contain the same elements. func ==<T : Equatable>(lhs: [T], rhs: [T]) -> Bool /// Two `ClosedInterval`\ s are equal if their `start` and `end` are /// equal func ==<T : Comparable>(lhs: ClosedInterval<T>, rhs: ClosedInterval<T>) -> Bool /// Two `HalfOpenInterval`\ s are equal if their `start` and `end` are /// equal func ==<T : Comparable>(lhs: HalfOpenInterval<T>, rhs: HalfOpenInterval<T>) -> Bool func ==(lhs: Character, rhs: Character) -> Bool /// Returns true if these arrays contain the same elements. func ==<T : Equatable>(lhs: ArraySlice<T>, rhs: ArraySlice<T>) -> Bool func ==<T : _RawOptionSetType>(a: T, b: T) -> Bool func ==<T>(lhs: UnsafeMutablePointer<T>, rhs: UnsafeMutablePointer<T>) -> Bool func ==<Key : Hashable, Value>(lhs: DictionaryIndex<Key, Value>, rhs: DictionaryIndex<Key, Value>) -> Bool func ==<I>(lhs: _ConcatenateForwardIndex<I>, rhs: _ConcatenateForwardIndex<I>) -> Bool func ==<I>(lhs: _ConcatenateBidirectionalIndex<I>, rhs: _ConcatenateBidirectionalIndex<I>) -> Bool func ==<Base : CollectionType>(lhs: FilterCollectionViewIndex<Base>, rhs: FilterCollectionViewIndex<Base>) -> Bool func ==<T : Hashable>(lhs: SetIndex<T>, rhs: SetIndex<T>) -> Bool func ==<Key : Equatable, Value : Equatable>(lhs: [Key : Value], rhs: [Key : Value]) -> Bool func ==(lhs: UInt8, rhs: UInt8) -> Bool func ==(lhs: Int8, rhs: Int8) -> Bool func ==(lhs: UInt16, rhs: UInt16) -> Bool func ==(lhs: Int16, rhs: Int16) -> Bool func ==<T : Hashable>(lhs: Set<T>, rhs: Set<T>) -> Bool /// Returns true if these arrays contain the same elements. func ==<T : Equatable>(lhs: ContiguousArray<T>, rhs: ContiguousArray<T>) -> Bool func ==(lhs: UInt32, rhs: UInt32) -> Bool func ==(lhs: Int32, rhs: Int32) -> Bool func ==(lhs: UInt64, rhs: UInt64) -> Bool func ==(lhs: Int64, rhs: Int64) -> Bool func ==<T>(lhs: UnsafePointer<T>, rhs: UnsafePointer<T>) -> Bool func ==(lhs: UInt, rhs: UInt) -> Bool func ==(lhs: Int, rhs: Int) -> Bool func ==(lhs: FloatingPointClassification, rhs: FloatingPointClassification) -> Bool func ==(lhs: Float80, rhs: Float80) -> Bool func ==(lhs: Double, rhs: Double) -> Bool func ==(lhs: Float, rhs: Float) -> Bool func ===(lhs: AnyObject?, rhs: AnyObject?) -> Bool func >(lhs: Float80, rhs: Float80) -> Bool func >(lhs: Double, rhs: Double) -> Bool func >(lhs: Float, rhs: Float) -> Bool func ><T : _Comparable>(lhs: T, rhs: T) -> Bool func >(lhs: UInt8, rhs: UInt8) -> Bool func >(lhs: Int8, rhs: Int8) -> Bool func >(lhs: UInt16, rhs: UInt16) -> Bool func >(lhs: Int16, rhs: Int16) -> Bool func >(lhs: Int, rhs: Int) -> Bool func >(lhs: UInt, rhs: UInt) -> Bool func >(lhs: UInt32, rhs: UInt32) -> Bool func >(lhs: Int64, rhs: Int64) -> Bool func ><T : _Comparable>(lhs: T?, rhs: T?) -> Bool func >(lhs: Int32, rhs: Int32) -> Bool func >(lhs: UInt64, rhs: UInt64) -> Bool func >=(lhs: UInt8, rhs: UInt8) -> Bool func >=(lhs: Int32, rhs: Int32) -> Bool func >=<T : _Comparable>(lhs: T?, rhs: T?) -> Bool func >=(lhs: Float, rhs: Float) -> Bool func >=(lhs: UInt16, rhs: UInt16) -> Bool func >=(lhs: Int8, rhs: Int8) -> Bool func >=(lhs: Double, rhs: Double) -> Bool func >=(lhs: Float80, rhs: Float80) -> Bool func >=(lhs: UInt32, rhs: UInt32) -> Bool func >=(lhs: Int16, rhs: Int16) -> Bool func >=(lhs: UInt64, rhs: UInt64) -> Bool func >=(lhs: Int64, rhs: Int64) -> Bool func >=(lhs: UInt, rhs: UInt) -> Bool func >=<T : _Comparable>(lhs: T, rhs: T) -> Bool func >=(lhs: Int, rhs: Int) -> Bool func >>(lhs: UInt8, rhs: UInt8) -> UInt8 func >>(lhs: Int16, rhs: Int16) -> Int16 func >>(lhs: UInt, rhs: UInt) -> UInt func >>(lhs: UInt64, rhs: UInt64) -> UInt64 func >>(lhs: Int32, rhs: Int32) -> Int32 func >>(lhs: UInt32, rhs: UInt32) -> UInt32 func >>(lhs: Int8, rhs: Int8) -> Int8 func >>(lhs: Int, rhs: Int) -> Int func >>(lhs: Int64, rhs: Int64) -> Int64 func >>(lhs: UInt16, rhs: UInt16) -> UInt16 func >>=(inout lhs: UInt16, rhs: UInt16) func >>=(inout lhs: UInt64, rhs: UInt64) func >>=(inout lhs: Int64, rhs: Int64) func >>=(inout lhs: Int8, rhs: Int8) func >>=(inout lhs: UInt, rhs: UInt) func >>=(inout lhs: UInt32, rhs: UInt32) func >>=(inout lhs: Int32, rhs: Int32) func >>=(inout lhs: Int, rhs: Int) func >>=(inout lhs: UInt8, rhs: UInt8) func >>=(inout lhs: Int16, rhs: Int16) func ??<T>(optional: T?, defaultValue: @autoclosure () -> T?) -> T? func ??<T>(optional: T?, defaultValue: @autoclosure () -> T) -> T /// A type that supports an "absolute value" function. protocol AbsoluteValuable : SignedNumberType { /// Returns the absolute value of `x` static func abs(x: Self) -> Self } /// The protocol to which all types implicitly conform typealias Any = protocol<> /// The protocol to which all class types implicitly conform. /// /// When used as a concrete type, all known `@objc` `class` methods and /// properties are available, as implicitly-unwrapped-optional methods /// and properties respectively, on each instance of `AnyClass`. For /// example: /// /// .. parsed-literal: /// /// class C { /// @objc class var cValue: Int { return 42 } /// } /// /// // If x has an @objc cValue: Int, return its value. /// // Otherwise, return nil. /// func getCValue(x: AnyClass) -> Int? { /// return **x.cValue** /// } /// /// See also: `AnyObject` typealias AnyClass = AnyObject.Type /// The protocol to which all classes implicitly conform. /// /// When used as a concrete type, all known `@objc` methods and /// properties are available, as implicitly-unwrapped-optional methods /// and properties respectively, on each instance of `AnyObject`. For /// example: /// /// .. parsed-literal: /// /// class C { /// @objc func getCValue() -> Int { return 42 } /// } /// /// // If x has a method @objc getValue()->Int, call it and /// // return the result. Otherwise, return nil. /// func getCValue1(x: AnyObject) -> Int? { /// if let f: ()->Int = **x.getCValue** { /// return f() /// } /// return nil /// } /// /// // A more idiomatic implementation using "optional chaining" /// func getCValue2(x: AnyObject) -> Int? { /// return **x.getCValue?()** /// } /// /// // An implementation that assumes the required method is present /// func getCValue3(x: AnyObject) -> **Int** { /// return **x.getCValue()** // x.getCValue is implicitly unwrapped. /// } /// /// See also: `AnyClass` @objc protocol AnyObject { } /// Conceptually_, `Array` is an efficient, tail-growable random-access /// collection of arbitrary elements. /// /// Common Properties of Array Types /// ================================ /// /// The information in this section applies to all three of Swift's /// array types, `Array<T>`, `ContiguousArray<T>`, and `ArraySlice<T>`. /// When you read the word "array" here in a normal typeface, it /// applies to all three of them. /// /// Value Semantics /// --------------- /// /// Each array variable, `let` binding, or stored property has an /// independent value that includes the values of all of its elements. /// Therefore, mutations to the array are not observable through its /// copies:: /// /// var a = [1, 2, 3] /// var b = a /// b[0] = 4 /// println("a=\(a), b=\(b)") // a=[1, 2, 3], b=[4, 2, 3] /// /// (Of course, if the array stores `class` references, the objects /// are shared; only the values of the references are independent) /// /// Arrays use Copy-on-Write so that their storage and elements are /// only copied lazily, upon mutation, when more than one array /// instance is using the same buffer. Therefore, the first in any /// sequence of mutating operations may cost `O(N)` time and space, /// where `N` is the length of the array. /// /// Growth and Capacity /// ------------------- /// /// When an array's contiguous storage fills up, new storage must be /// allocated and elements must be moved to the new storage. `Array`, /// `ContiguousArray`, and `ArraySlice` share an exponential growth /// strategy that makes `append` a constant time operation *when /// amortized over many invocations*. In addition to a `count` /// property, these array types have a `capacity` that reflects their /// potential to store elements without reallocation, and when you /// know how many elements you'll store, you can call /// `reserveCapacity` to pre-emptively reallocate and prevent /// intermediate reallocations. /// /// .. _Conceptually: /// /// Objective-C Bridge /// ================== /// /// The main distinction between `Array` and the other array types is /// that it interoperates seamlessly and efficiently with Objective-C. /// /// `Array<T>` is considered bridged to Objective-C iff `T` is bridged /// to Objective-C. /// /// When `T` is a `class` or `@objc` protocol type, `Array` may store /// its elements in an `NSArray`. Since any arbitrary subclass of /// `NSArray` can become an `Array`, there are no guarantees about /// representation or efficiency in this case (see also /// `ContiguousArray`). Since `NSArray` is immutable, it is just as /// though the storage was shared by some copy: the first in any /// sequence of mutating operations causes elements to be copied into /// unique, contiguous storage which may cost `O(N)` time and space, /// where `N` is the length of the array (or more, if the underlying /// `NSArray` is has unusual performance characteristics). /// /// Bridging to Objective-C /// ----------------------- /// /// Any bridged `Array` can be implicitly converted to an `NSArray`. /// When `T` is a `class` or `@objc` protocol, bridging takes O(1) /// time and O(1) space. Other `Array`\ s must be bridged /// element-by-element, allocating a new object for each element, at a /// cost of at least O(`count`) time and space. /// /// Bridging from Objective-C /// ------------------------- /// /// An `NSArray` can be implicitly or explicitly converted to any /// bridged `Array<T>`. This conversion calls `copyWithZone` on the /// `NSArray`, to ensure it won't be modified, and stores the result /// in the `Array`. Type-checking, to ensure the `NSArray`\ 's /// elements match or can be bridged to `T`, is deferred until the /// first element access. struct Array<T> : MutableCollectionType, Sliceable, _DestructorSafeContainer { /// The type of element stored by this `Array` typealias Element = T /// Always zero, which is the index of the first element when non-empty. var startIndex: Int { get } /// A "past-the-end" element index; the successor of the last valid /// subscript argument. var endIndex: Int { get } subscript (index: Int) -> T /// Return a *generator* over the elements. /// /// Complexity: O(1) func generate() -> IndexingGenerator<[T]> /// A type that can represent a sub-range of an `Array` typealias SubSlice = ArraySlice<T> subscript (subRange: Range<Int>) -> ArraySlice<T> /// Initialization from an existing buffer does not have "array.init" /// semantics because the caller may retain an alias to buffer. //init(_ buffer: _ArrayBuffer<T>) } extension Array : __ArrayType { } extension Array : ArrayLiteralConvertible { /// Create an instance containing `elements`. init(arrayLiteral elements: T...) } extension Array : _ArrayType { /// Construct an empty Array init() /// Construct from an arbitrary sequence with elements of type `T` init<S : SequenceType>(_ s: S) /// Construct a Array of `count` elements, each initialized to /// `repeatedValue`. init(count: Int, repeatedValue: T) /// How many elements the Array stores var count: Int { get } /// How many elements the `Array` can store without reallocation var capacity: Int { get } /// `true` if and only if the `Array` is empty var isEmpty: Bool { get } /// The first element, or `nil` if the array is empty var first: T? { get } /// The last element, or `nil` if the array is empty var last: T? { get } /// Reserve enough space to store minimumCapacity elements. /// /// PostCondition: `capacity >= minimumCapacity` and the array has /// mutable contiguous storage. /// /// Complexity: O(`count`) mutating func reserveCapacity(minimumCapacity: Int) /// Append newElement to the Array /// /// Complexity: amortized O(1) unless `self`'s storage is shared with another live array; O(`count`) if `self` does not wrap a bridged `NSArray`; otherwise the efficiency is unspecified. mutating func append(newElement: T) /// Append the elements of `newElements` to `self`. /// /// Complexity: O(*length of result*) /// mutating func extend<S : SequenceType>(newElements: S) /// Remove an element from the end of the Array in O(1). /// Requires: count > 0 mutating func removeLast() -> T /// Insert `newElement` at index `i`. /// /// Requires: `i <= count` /// /// Complexity: O(\ `count`\ ). mutating func insert(newElement: T, atIndex i: Int) /// Remove and return the element at index `i` /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count`\ ). mutating func removeAtIndex(index: Int) -> T /// Remove all elements. /// /// Postcondition: `capacity == 0` iff `keepCapacity` is `false`. /// /// Complexity: O(\ `count(self)`\ ). mutating func removeAll(keepCapacity: Bool) /// Interpose `self` between each consecutive pair of `elements`, /// and concatenate the elements of the resulting sequence. For /// example, `[-1, -2].join([[1, 2, 3], [4, 5, 6], [7, 8, 9]])` /// yields `[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]` // TODO: func join<S : SequenceType where [T] == [T]>(elements: S) -> [T] func join<S : SequenceType >(elements: S) -> [T] /// Return the result of repeatedly calling `combine` with an /// accumulated value initialized to `initial` and each element of /// `self`, in turn, i.e. return /// `combine(combine(...combine(combine(initial, self[0]), /// self[1]),...self[count-2]), self[count-1])`. func reduce<U>(initial: U, combine: @noescape (U, T) -> U) -> U /// Sort `self` in-place according to `isOrderedBefore`. Requires: /// `isOrderedBefore` induces a `strict weak ordering /// <http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings>`__ /// over the elements. mutating func sort(isOrderedBefore: (T, T) -> Bool) /// Return a copy of `self` that has been sorted according to /// `isOrderedBefore`. Requires: `isOrderedBefore` induces a /// `strict weak ordering /// <http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings>`__ /// over the elements. func sorted(isOrderedBefore: (T, T) -> Bool) -> [T] /// Return an `Array` containing the results of calling /// `transform(x)` on each element `x` of `self` func map<U>(transform: (T) -> U) -> [U] /// Return an `Array` containing the results of calling /// `transform(x)` on each element `x` of `self` and flattening the result. func flatMap<U>(transform: @noescape (T) -> [U]) -> [U] /// A Array containing the elements of `self` in reverse order func reverse() -> [T] /// Return an `Array` containing the elements `x` of `self` for which /// `includeElement(x)` is `true` func filter(includeElement: (T) -> Bool) -> [T] } extension Array : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension Array : Printable, DebugPrintable { /// A textual representation of `self`. var description: String { get } /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } extension Array { /// Call `body(p)`, where `p` is a pointer to the `Array`\ 's /// contiguous storage. If no such storage exists, it is first created. /// /// Often, the optimizer can eliminate bounds checks within an /// array algorithm, but when that fails, invoking the /// same algorithm on `body`\ 's argument lets you trade safety for /// speed. func withUnsafeBufferPointer<R>(body: @noescape (UnsafeBufferPointer<T>) -> R) -> R /// Call `body(p)`, where `p` is a pointer to the `Array`\ 's /// mutable contiguous storage. If no such storage exists, it is first created. /// /// Often, the optimizer can eliminate bounds- and uniqueness-checks /// within an array algorithm, but when that fails, invoking the /// same algorithm on `body`\ 's argument lets you trade safety for /// speed. mutating func withUnsafeMutableBufferPointer<R>(body: @noescape (inout UnsafeMutableBufferPointer<T>) -> R) -> R } extension Array { /// Replace the given `subRange` of elements with `newElements`. /// /// Complexity: O(\ `count(subRange)`\ ) if `subRange.endIndex /// == self.endIndex` and `isEmpty(newElements)`\ , O(N) otherwise. mutating func replaceRange<C : CollectionType>(subRange: Range<Int>, with newElements: C) /// Insert `newElements` at index `i` /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count + count(newElements)`\ ). mutating func splice<S : CollectionType>(newElements: S, atIndex i: Int) /// Remove the indicated `subRange` of elements /// /// Complexity: O(\ `count`\ ). mutating func removeRange(subRange: Range<Int>) } extension Array { /// Construct from the given `_NSArrayCoreType`. /// /// If `noCopy` is `true`, either `source` must be known to be immutable, /// or the resulting `Array` must not survive across code that could mutate /// `source`. init(_fromCocoaArray source: _NSArrayCoreType, noCopy: Bool) } /// Conforming types can be initialized with array literals protocol ArrayLiteralConvertible { typealias Element /// Create an instance initialized with `elements`. init(arrayLiteral elements: Element...) } struct _SliceBuffer<T> { } /// The `Array`-like type that represents a sub-sequence of any /// `Array`, `ContiguousArray`, or other `ArraySlice`. /// /// `ArraySlice` always uses contiguous storage and does not bridge to /// Objective-C. /// /// .. Warning:: Long-term storage of `ArraySlice` instances is discouraged /// /// Because a `ArraySlice` presents a *view* onto the storage of some /// larger array even after the original array's lifetime ends, /// storing the slice may prolong the lifetime of elements that are /// no longer accessible, which can manifest as apparent memory and /// object leakage. To prevent this effect, use `ArraySlice` only for /// transient computation. struct ArraySlice<T> : MutableCollectionType, Sliceable, _DestructorSafeContainer { /// The type of element stored by this `ArraySlice` typealias Element = T /// Always zero, which is the index of the first element when non-empty. var startIndex: Int { get } /// A "past-the-end" element index; the successor of the last valid /// subscript argument. var endIndex: Int { get } subscript (index: Int) -> T /// Return a *generator* over the elements. /// /// Complexity: O(1) func generate() -> IndexingGenerator<ArraySlice<T>> /// A type that can represent a sub-range of an `ArraySlice` typealias SubSlice = ArraySlice<T> subscript (subRange: Range<Int>) -> ArraySlice<T> /// Initialization from an existing buffer does not have "array.init" /// semantics because the caller may retain an alias to buffer. init(_ buffer: _SliceBuffer<T>) } extension ArraySlice : __ArrayType { } extension ArraySlice : ArrayLiteralConvertible { /// Create an instance containing `elements`. init(arrayLiteral elements: T...) } extension ArraySlice : _ArrayType { /// Construct an empty ArraySlice init() /// Construct from an arbitrary sequence with elements of type `T` init<S : SequenceType>(_ s: S) /// Construct a ArraySlice of `count` elements, each initialized to /// `repeatedValue`. init(count: Int, repeatedValue: T) /// How many elements the ArraySlice stores var count: Int { get } /// How many elements the `ArraySlice` can store without reallocation var capacity: Int { get } /// `true` if and only if the `ArraySlice` is empty var isEmpty: Bool { get } /// The first element, or `nil` if the array is empty var first: T? { get } /// The last element, or `nil` if the array is empty var last: T? { get } /// Reserve enough space to store minimumCapacity elements. /// /// PostCondition: `capacity >= minimumCapacity` and the array has /// mutable contiguous storage. /// /// Complexity: O(`count`) mutating func reserveCapacity(minimumCapacity: Int) /// Append newElement to the ArraySlice /// /// Complexity: amortized O(1) unless `self`'s storage is shared with another live array; O(`count`) otherwise. mutating func append(newElement: T) /// Append the elements of `newElements` to `self`. /// /// Complexity: O(*length of result*) /// mutating func extend<S : SequenceType>(newElements: S) /// Remove an element from the end of the ArraySlice in O(1). /// Requires: count > 0 mutating func removeLast() -> T /// Insert `newElement` at index `i`. /// /// Requires: `i <= count` /// /// Complexity: O(\ `count`\ ). mutating func insert(newElement: T, atIndex i: Int) /// Remove and return the element at index `i` /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count`\ ). mutating func removeAtIndex(index: Int) -> T /// Remove all elements. /// /// Postcondition: `capacity == 0` iff `keepCapacity` is `false`. /// /// Complexity: O(\ `count(self)`\ ). mutating func removeAll(keepCapacity: Bool) /// Interpose `self` between each consecutive pair of `elements`, /// and concatenate the elements of the resulting sequence. For /// example, `[-1, -2].join([[1, 2, 3], [4, 5, 6], [7, 8, 9]])` /// yields `[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]` func join<S : SequenceType>(elements: S) -> ArraySlice<T> /// Return the result of repeatedly calling `combine` with an /// accumulated value initialized to `initial` and each element of /// `self`, in turn, i.e. return /// `combine(combine(...combine(combine(initial, self[0]), /// self[1]),...self[count-2]), self[count-1])`. func reduce<U>(initial: U, combine: @noescape (U, T) -> U) -> U /// Sort `self` in-place according to `isOrderedBefore`. Requires: /// `isOrderedBefore` induces a `strict weak ordering /// <http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings>`__ /// over the elements. mutating func sort(isOrderedBefore: (T, T) -> Bool) /// Return a copy of `self` that has been sorted according to /// `isOrderedBefore`. Requires: `isOrderedBefore` induces a /// `strict weak ordering /// <http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings>`__ /// over the elements. func sorted(isOrderedBefore: (T, T) -> Bool) -> ArraySlice<T> /// Return an `ArraySlice` containing the results of calling /// `transform(x)` on each element `x` of `self` func map<U>(transform: (T) -> U) -> ArraySlice<U> /// Return an `ArraySlice` containing the results of calling /// `transform(x)` on each element `x` of `self` and flattening the result. func flatMap<U>(transform: @noescape (T) -> ArraySlice<U>) -> ArraySlice<U> /// A ArraySlice containing the elements of `self` in reverse order func reverse() -> ArraySlice<T> /// Return an `ArraySlice` containing the elements `x` of `self` for which /// `includeElement(x)` is `true` func filter(includeElement: (T) -> Bool) -> ArraySlice<T> } extension ArraySlice : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension ArraySlice : Printable, DebugPrintable { /// A textual representation of `self`. var description: String { get } /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } extension ArraySlice { /// Call `body(p)`, where `p` is a pointer to the `ArraySlice`\ 's /// contiguous storage. /// /// Often, the optimizer can eliminate bounds checks within an /// array algorithm, but when that fails, invoking the /// same algorithm on `body`\ 's argument lets you trade safety for /// speed. func withUnsafeBufferPointer<R>(body: @noescape (UnsafeBufferPointer<T>) -> R) -> R /// Call `body(p)`, where `p` is a pointer to the `ArraySlice`\ 's /// mutable contiguous storage. /// /// Often, the optimizer can eliminate bounds- and uniqueness-checks /// within an array algorithm, but when that fails, invoking the /// same algorithm on `body`\ 's argument lets you trade safety for /// speed. mutating func withUnsafeMutableBufferPointer<R>(body: @noescape (inout UnsafeMutableBufferPointer<T>) -> R) -> R } extension ArraySlice { /// Replace the given `subRange` of elements with `newElements`. /// /// Complexity: O(\ `count(subRange)`\ ) if `subRange.endIndex /// == self.endIndex` and `isEmpty(newElements)`\ , O(N) otherwise. mutating func replaceRange<C : CollectionType>(subRange: Range<Int>, with newElements: C) /// Insert `newElements` at index `i` /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count + count(newElements)`\ ). mutating func splice<S : CollectionType>(newElements: S, atIndex i: Int) /// Remove the indicated `subRange` of elements /// /// Complexity: O(\ `count`\ ). mutating func removeRange(subRange: Range<Int>) } /// A mutable pointer-to-ObjC-pointer argument. /// /// This type has implicit conversions to allow passing any of the following /// to a C or ObjC API: /// /// - 'nil', which gets passed as a null pointer, /// - an inout argument of the referenced type, which gets passed as a pointer /// to a writeback temporary with autoreleasing ownership semantics, /// - an UnsafeMutablePointer<T>, which is passed as-is. /// /// Passing pointers to mutable arrays of ObjC class pointers is not /// directly supported. Unlike UnsafeMutablePointer<T>, /// AutoreleasingUnsafeMutablePointer must reference storage that does /// not own a reference count to the referenced /// value. UnsafeMutablePointer's operations, by contrast, assume that /// the referenced storage owns values loaded from or stored to it. /// /// This type does not carry an owner pointer unlike the other C*Pointer types /// because it only needs to reference the results of inout conversions, which /// already have writeback-scoped lifetime. struct AutoreleasingUnsafeMutablePointer<T> : Equatable, NilLiteralConvertible, _PointerType { /// Access the underlying raw memory, getting and /// setting values. var memory: T { get nonmutating set } subscript (i: Int) -> T { get } /// Create an instance initialized with `nil`. init(nilLiteral: ()) /// Initialize to a null pointer. init() /// Explicit construction from an UnsafeMutablePointer. /// /// This is inherently unsafe; UnsafeMutablePointer assumes the /// referenced memory has +1 strong ownership semantics, whereas /// AutoreleasingUnsafeMutablePointer implies +0 semantics. init<U>(_ ptr: UnsafeMutablePointer<U>) } extension AutoreleasingUnsafeMutablePointer : DebugPrintable { /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } extension AutoreleasingUnsafeMutablePointer : CVarArgType { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// An *index* that can step backwards via application of its /// `predecessor()` method. protocol BidirectionalIndexType : ForwardIndexType, _BidirectionalIndexType { } /// The lazy `CollectionType` returned by `reverse(c)` where `c` is a /// `CollectionType` with an `Index` conforming to `BidirectionalIndexType` struct BidirectionalReverseView<T : CollectionType where T.Index : BidirectionalIndexType> : CollectionType { /// 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. typealias Index = ReverseBidirectionalIndex<T.Index> /// A type whose instances can produce the elements of this /// sequence, in order. typealias Generator = IndexingGenerator<BidirectionalReverseView<T>> /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> IndexingGenerator<BidirectionalReverseView<T>> /// The position of the first element in a non-empty collection. /// /// Identical to `endIndex` in an empty collection. var startIndex: Index { get } /// 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()`. var endIndex: Index { get } subscript (position: Index) -> T.Generator.Element { get } } /// A `RandomAccessIndexType` that has two possible values. Used as /// the `Index` type for `SequenceOfOne<T>`. enum Bit : Int, RandomAccessIndexType, Reflectable { case Zero case One /// Returns the next consecutive value after `self`. /// /// Requires: `self == .Zero`. func successor() -> Bit /// Returns the previous consecutive value before `self`. /// /// Requires: `self != .Zero`. func predecessor() -> Bit /// Return the minimum number of applications of `successor` or /// `predecessor` required to reach `other` from `self`. /// /// Complexity: O(1). func distanceTo(other: Bit) -> Int /// Return `self` offset by `n` steps. /// /// :returns: If `n > 0`, the result of applying `successor` to /// `self` `n` times. If `n < 0`, the result of applying /// `predecessor` to `self` `-n` times. Otherwise, `self`. /// /// Complexity: O(1) func advancedBy(distance: Int) -> Bit /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension Bit : IntegerArithmeticType { /// Add `lhs` and `rhs`, returning a result and a `Bool` that is /// true iff the operation caused an arithmetic overflow. static func addWithOverflow(lhs: Bit, _ rhs: Bit) -> (Bit, overflow: Bool) /// Subtract `lhs` and `rhs`, returning a result and a `Bool` that is /// true iff the operation caused an arithmetic overflow. static func subtractWithOverflow(lhs: Bit, _ rhs: Bit) -> (Bit, overflow: Bool) /// Multiply `lhs` and `rhs`, returning a result and a `Bool` that is /// true iff the operation caused an arithmetic overflow. static func multiplyWithOverflow(lhs: Bit, _ rhs: Bit) -> (Bit, overflow: Bool) /// Divide `lhs` and `rhs`, returning a result and a `Bool` that is /// true iff the operation caused an arithmetic overflow. static func divideWithOverflow(lhs: Bit, _ rhs: Bit) -> (Bit, overflow: Bool) /// Divide `lhs` and `rhs`, returning the remainder and a `Bool` that is /// true iff the operation caused an arithmetic overflow. static func remainderWithOverflow(lhs: Bit, _ rhs: Bit) -> (Bit, overflow: Bool) /// Represent this number using Swift's widest native signed integer /// type. func toIntMax() -> IntMax } /// A set type with O(1) standard bitwise operators. /// /// Each instance is a subset of `~Self.allZeros` /// /// Axioms, where `x` is an instance of `Self`:: /// /// x | Self.allZeros == x /// x ^ Self.allZeros == x /// x & Self.allZeros == .allZeros /// x & ~Self.allZeros == x /// ~x == x ^ ~Self.allZeros protocol BitwiseOperationsType { /// Returns the intersection of bits set in `lhs` and `rhs`. /// /// Complexity: O(1) func &(lhs: Self, rhs: Self) -> Self /// Returns the union of bits set in `lhs` and `rhs` /// /// Complexity: O(1) func |(lhs: Self, rhs: Self) -> Self /// Returns the bits that are set in exactly one of `lhs` and `rhs` /// /// Complexity: O(1) func ^(lhs: Self, rhs: Self) -> Self /// Returns `x ^ ~Self.allZeros` /// /// Complexity: O(1) prefix func ~(x: Self) -> Self /// The empty bitset. /// /// Also the `identity element /// <http://en.wikipedia.org/wiki/Identity_element>`_ for `|` and /// `^`, and the `fixed point /// <http://en.wikipedia.org/wiki/Fixed_point_(mathematics)>`_ for /// `&`. static var allZeros: Self { get } } /// A value type whose instances are either `true` or `false`. struct Bool { /// Default-initialize Boolean value to `false`. init() } extension Bool : BooleanLiteralConvertible { init(_builtinBooleanLiteral value: Builtin.Int1) /// Create an instance initialized to `value`. init(booleanLiteral value: Bool) } extension Bool : BooleanType { /// Identical to `self`. var boolValue: Bool { get } /// Construct an instance representing the same logical value as /// `value` init<T : BooleanType>(_ value: T) } extension Bool : Printable { /// A textual representation of `self`. var description: String { get } } extension Bool : Equatable, Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } extension Bool : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } /// Conforming types can be initialized with the boolean literals /// `true` and `false`. protocol BooleanLiteralConvertible { /// Create an instance initialized to `value`. init(booleanLiteral value: BooleanLiteralType) } /// The default type for an otherwise-unconstrained boolean literal typealias BooleanLiteralType = Bool /// A type that represents a boolean value. /// /// Types that conform to the `BooleanType` protocol can be used as /// the condition in control statements (`if`, `while`, C-style `for`) /// and other logical value contexts (e.g., `case` statement guards). /// /// Only two types provided by Swift, `Bool` and `ObjCBool`, conform /// to `BooleanType`. Expanding this set to include types that /// represent more than simple boolean values is discouraged. protocol BooleanType { /// The value of `self`, expressed as a `Bool`. var boolValue: Bool { get } } /// The C '_Bool' and C++ 'bool' type. typealias CBool = Bool /// The C 'char' type. /// /// This will be the same as either `CSignedChar` (in the common /// case) or `CUnsignedChar`, depending on the platform. typealias CChar = Int8 /// The C++11 'char16_t' type, which has UTF-16 encoding. typealias CChar16 = UInt16 /// The C++11 'char32_t' type, which has UTF-32 encoding. typealias CChar32 = UnicodeScalar /// The C 'double' type. typealias CDouble = Double /// The C 'float' type. typealias CFloat = Float /// The family of C function pointer types. /// /// In imported APIs, `T` is a Swift function type such as /// `(Int)->String`. /// /// Though not directly useful in Swift, `CFunctionPointer<T>` can be /// used to safely pass a C function pointer, received from one C or /// Objective-C API, to another C or Objective-C API. struct CFunctionPointer<T> : Equatable, Hashable, NilLiteralConvertible { /// Create a `nil` instance. init() /// Reinterpret the bits of `value` as `CFunctionPointer<T>`. /// /// .. Warning:: This is a fundamentally unsafe operation, equivalent to /// `unsafeBitCast(value, CFunctionPointer<T>.self)` init(_ value: COpaquePointer) /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } /// Create an instance initialized with `nil`. init(nilLiteral: ()) } extension CFunctionPointer : DebugPrintable { /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } extension CFunctionPointer : CVarArgType { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// The C 'int' type. typealias CInt = Int32 /// The C 'long' type. typealias CLong = Int /// The C 'long long' type. typealias CLongLong = Int64 /// A wrapper around an opaque C pointer. /// /// Opaque pointers are used to represent C pointers to types that /// cannot be represented in Swift, such as incomplete struct types. struct COpaquePointer : Equatable, Hashable, NilLiteralConvertible { /// Construct a `nil` instance. init() /// Construct a `COpaquePointer` from a given address in memory. /// /// This is a fundamentally unsafe conversion. init(bitPattern: Word) /// Construct a `COpaquePointer` from a given address in memory. /// /// This is a fundamentally unsafe conversion. init(bitPattern: UWord) /// Convert a typed `UnsafePointer` to an opaque C pointer. init<T>(_ source: UnsafePointer<T>) /// Convert a typed `UnsafeMutablePointer` to an opaque C pointer. init<T>(_ source: UnsafeMutablePointer<T>) /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } /// Create an instance initialized with `nil`. init(nilLiteral: ()) } extension COpaquePointer : DebugPrintable { /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } extension COpaquePointer { /// Reinterpret the bits of `value` as `COpaquePointer`. /// /// .. Warning:: This is a fundamentally unsafe operation, equivalent to /// `unsafeBitCast(value, COpaquePointer.self)` init<T>(_ value: CFunctionPointer<T>) } extension COpaquePointer : CVarArgType { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// The C 'short' type. typealias CShort = Int16 /// The C 'signed char' type. typealias CSignedChar = Int8 /// The C 'unsigned char' type. typealias CUnsignedChar = UInt8 /// The C 'unsigned int' type. typealias CUnsignedInt = UInt32 /// The C 'unsigned long' type. typealias CUnsignedLong = UInt /// The C 'unsigned long long' type. typealias CUnsignedLongLong = UInt64 /// The C 'unsigned short' type. typealias CUnsignedShort = UInt16 /// The corresponding Swift type to `va_list` in imported C APIs. struct CVaListPointer { init(_fromUnsafeMutablePointer from: UnsafeMutablePointer<Void>) } extension CVaListPointer : DebugPrintable { /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } /// Instances of conforming types can be encoded, and appropriately /// passed, as elements of a C `va_list`. /// /// This protocol is useful in presenting C "varargs" APIs natively in /// Swift. It only works for APIs that have a `va_list` variant, so /// for example, it isn't much use if all you have is:: /// /// int f(int n, ...) /// /// Given a version like this, though, :: /// /// int f(int, va_list arguments) /// /// you can write:: /// /// func swiftF(x: Int, arguments: CVarArgType...) -> Int { /// return withVaList(arguments) { f(x, $0) } /// } protocol CVarArgType { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// The C++ 'wchar_t' type. typealias CWideChar = UnicodeScalar /// `Character` represents some Unicode grapheme cluster as /// defined by a canonical, localized, or otherwise tailored /// segmentation algorithm. struct Character : ExtendedGraphemeClusterLiteralConvertible, Equatable, Hashable, Comparable { /// Construct a `Character` containing just the given `scalar`. init(_ scalar: UnicodeScalar) init(_builtinUnicodeScalarLiteral value: Builtin.Int32) /// Create an instance initialized to `value`. init(unicodeScalarLiteral value: Character) init(_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, byteSize: Builtin.Word, isASCII: Builtin.Int1) /// Create an instance initialized to `value`. init(extendedGraphemeClusterLiteral value: Character) /// Create an instance from a single-character `String`. /// /// Requires: `s` contains exactly one extended grapheme cluster. init(_ s: String) /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } extension Character : DebugPrintable { /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } extension Character : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension Character : Streamable { /// Write a textual representation of `self` into `target` func writeTo<Target : OutputStreamType>(inout target: Target) } /// A closed `IntervalType`, which contains both its `start` and its /// `end`. Cannot represent an empty interval. struct ClosedInterval<T : Comparable> : IntervalType, Equatable, Printable, DebugPrintable, Reflectable { /// The type of the `Interval`\ 's endpoints typealias Bound = T /// Construct a copy of `x` init(_ x: ClosedInterval<T>) /// Construct an interval with the given bounds. Requires: `start` /// <= `end`. init(_ start: T, _ end: T) /// The `Interval`\ 's lower bound. Invariant: `start` <= `end` var start: T { get } /// The `Interval`\ 's upper bound. Invariant: `start` <= `end` var end: T { get } /// A textual representation of `self`. var description: String { get } /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } /// Returns `true` iff the `Interval` contains `x` func contains(x: T) -> Bool /// Return `intervalToClamp` clamped to `self`. The bounds of the /// result, even if it is empty, are always limited to the bounds of /// `self` func clamp(intervalToClamp: ClosedInterval<T>) -> ClosedInterval<T> /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension ClosedInterval { /// `true` iff the `Interval` is empty. In the case of /// `ClosedInterval`, always returns `false` var isEmpty: Bool { get } } /// A collection containing a single element of type `T`. struct CollectionOfOne<T> : CollectionType { /// 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. typealias Index = Bit /// Construct an instance containing just `element`. init(_ element: T) /// The position of the first element. var startIndex: Index { get } /// The "past the end" position; always identical to /// `startIndex.successor()`. /// /// Note: `endIndex` is not a valid argument to `subscript`. var endIndex: Index { get } /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> GeneratorOfOne<T> subscript (position: Index) -> T { get } } extension CollectionOfOne : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } /// A multi-pass *sequence* with addressable positions. /// /// Positions are represented by an associated `Index` type. Whereas /// an arbitrary *sequence* may be consumed as it is traversed, a /// *collection* is multi-pass: any element may be revisited merely by /// saving its index. /// /// The sequence view of the elements is identical to the collection /// view. In other words, the following code binds the same series of /// values to `x` as does `for x in self {}`:: /// /// for i in startIndex..<endIndex { /// let x = self[i] /// } protocol CollectionType : _CollectionType, SequenceType { subscript (position: Self.Index) -> Self.Generator.Element { get } } /// Instances of conforming types can be compared using relational /// operators, which define a `strict total order /// <http://en.wikipedia.org/wiki/Total_order#Strict_total_order>`_. /// /// A type conforming to `Comparable` need only supply the `<` and /// `==` operators; default implementations of `<=`, `>`, `>=`, and /// `!=` are supplied by the standard library:: /// /// struct Singular : Comparable {} /// func ==(x: Singular, y: Singular) -> Bool { return true } /// func <(x: Singular, y: Singular) -> Bool { return false } /// /// **Axioms**, in addition to those of `Equatable`: /// /// - `x == y` implies `x <= y`, `x >= y`, `!(x < y)`, and `!(x > y)` /// - `x < y` implies `x <= y` and `y > x` /// - `x > y` implies `x >= y` and `y < x` /// - `x <= y` implies `y >= x` /// - `x >= y` implies `y <= x` protocol Comparable : _Comparable, Equatable { func <=(lhs: Self, rhs: Self) -> Bool func >=(lhs: Self, rhs: Self) -> Bool func >(lhs: Self, rhs: Self) -> Bool } /// A fast, contiguously-stored array of `T`. /// /// Efficiency is equivalent to that of `Array`, unless `T` is a /// `class` or `@objc` `protocol` type, in which case using /// `ContiguousArray` may be more efficient. Note, however, that /// `ContiguousArray` does not bridge to Objective-C. See `Array`, /// with which `ContiguousArray` shares most properties, for more /// detail. struct ContiguousArray<T> : MutableCollectionType, Sliceable, _DestructorSafeContainer { /// The type of element stored by this `ContiguousArray` typealias Element = T /// Always zero, which is the index of the first element when non-empty. var startIndex: Int { get } /// A "past-the-end" element index; the successor of the last valid /// subscript argument. var endIndex: Int { get } subscript (index: Int) -> T /// Return a *generator* over the elements. /// /// Complexity: O(1) func generate() -> IndexingGenerator<ContiguousArray<T>> /// A type that can represent a sub-range of a ContiguousArray typealias SubSlice = ArraySlice<T> subscript (subRange: Range<Int>) -> ArraySlice<T> /// Initialization from an existing buffer does not have "array.init" /// semantics because the caller may retain an alias to buffer. init(_ buffer: _ContiguousArrayBuffer<T>) } extension ContiguousArray : __ArrayType { } extension ContiguousArray : ArrayLiteralConvertible { /// Create an instance containing `elements`. init(arrayLiteral elements: T...) } extension ContiguousArray : _ArrayType { /// Construct an empty ContiguousArray init() /// Construct from an arbitrary sequence with elements of type `T` init<S : SequenceType>(_ s: S) /// Construct a ContiguousArray of `count` elements, each initialized to /// `repeatedValue`. init(count: Int, repeatedValue: T) /// How many elements the ContiguousArray stores var count: Int { get } /// How many elements the `ContiguousArray` can store without reallocation var capacity: Int { get } /// `true` if and only if the `ContiguousArray` is empty var isEmpty: Bool { get } /// The first element, or `nil` if the array is empty var first: T? { get } /// The last element, or `nil` if the array is empty var last: T? { get } /// Reserve enough space to store minimumCapacity elements. /// /// PostCondition: `capacity >= minimumCapacity` and the array has /// mutable contiguous storage. /// /// Complexity: O(`count`) mutating func reserveCapacity(minimumCapacity: Int) /// Append newElement to the ContiguousArray /// /// Complexity: amortized O(1) unless `self`'s storage is shared with another live array; O(`count`) otherwise. mutating func append(newElement: T) /// Append the elements of `newElements` to `self`. /// /// Complexity: O(*length of result*) /// mutating func extend<S : SequenceType>(newElements: S) /// Remove an element from the end of the ContiguousArray in O(1). /// Requires: count > 0 mutating func removeLast() -> T /// Insert `newElement` at index `i`. /// /// Requires: `i <= count` /// /// Complexity: O(\ `count`\ ). mutating func insert(newElement: T, atIndex i: Int) /// Remove and return the element at index `i` /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count`\ ). mutating func removeAtIndex(index: Int) -> T /// Remove all elements. /// /// Postcondition: `capacity == 0` iff `keepCapacity` is `false`. /// /// Complexity: O(\ `count(self)`\ ). mutating func removeAll(keepCapacity: Bool) /// Interpose `self` between each consecutive pair of `elements`, /// and concatenate the elements of the resulting sequence. For /// example, `[-1, -2].join([[1, 2, 3], [4, 5, 6], [7, 8, 9]])` /// yields `[1, 2, 3, -1, -2, 4, 5, 6, -1, -2, 7, 8, 9]` func join<S : SequenceType>(elements: S) -> ContiguousArray<T> /// Return the result of repeatedly calling `combine` with an /// accumulated value initialized to `initial` and each element of /// `self`, in turn, i.e. return /// `combine(combine(...combine(combine(initial, self[0]), /// self[1]),...self[count-2]), self[count-1])`. func reduce<U>(initial: U, combine: @noescape (U, T) -> U) -> U /// Sort `self` in-place according to `isOrderedBefore`. Requires: /// `isOrderedBefore` induces a `strict weak ordering /// <http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings>`__ /// over the elements. mutating func sort(isOrderedBefore: (T, T) -> Bool) /// Return a copy of `self` that has been sorted according to /// `isOrderedBefore`. Requires: `isOrderedBefore` induces a /// `strict weak ordering /// <http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings>`__ /// over the elements. func sorted(isOrderedBefore: (T, T) -> Bool) -> ContiguousArray<T> /// Return a ContiguousArray containing the results of calling /// `transform(x)` on each element `x` of `self` func map<U>(transform: (T) -> U) -> ContiguousArray<U> /// Return a ContiguousArray containing the results of calling /// `transform(x)` on each element `x` of `self` and flattening the result. func flatMap<U>(transform: @noescape (T) -> ContiguousArray<U>) -> ContiguousArray<U> /// A ContiguousArray containing the elements of `self` in reverse order func reverse() -> ContiguousArray<T> /// Return a ContiguousArray containing the elements `x` of `self` for which /// `includeElement(x)` is `true` func filter(includeElement: (T) -> Bool) -> ContiguousArray<T> } extension ContiguousArray : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension ContiguousArray : Printable, DebugPrintable { /// A textual representation of `self`. var description: String { get } /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } extension ContiguousArray { /// Call `body(p)`, where `p` is a pointer to the `ContiguousArray`\ 's /// contiguous storage. /// /// Often, the optimizer can eliminate bounds checks within an /// array algorithm, but when that fails, invoking the /// same algorithm on `body`\ 's argument lets you trade safety for /// speed. func withUnsafeBufferPointer<R>(body: @noescape (UnsafeBufferPointer<T>) -> R) -> R /// Call `body(p)`, where `p` is a pointer to the `ContiguousArray`\ 's /// mutable contiguous storage. /// /// Often, the optimizer can eliminate bounds- and uniqueness-checks /// within an array algorithm, but when that fails, invoking the /// same algorithm on `body`\ 's argument lets you trade safety for /// speed. mutating func withUnsafeMutableBufferPointer<R>(body: @noescape (inout UnsafeMutableBufferPointer<T>) -> R) -> R } extension ContiguousArray { /// Replace the given `subRange` of elements with `newElements`. /// /// Complexity: O(\ `count(subRange)`\ ) if `subRange.endIndex /// == self.endIndex` and `isEmpty(newElements)`\ , O(N) otherwise. mutating func replaceRange<C : CollectionType>(subRange: Range<Int>, with newElements: C) /// Insert `newElements` at index `i` /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count + count(newElements)`\ ). mutating func splice<S : CollectionType>(newElements: S, atIndex i: Int) /// Remove the indicated `subRange` of elements /// /// Complexity: O(\ `count`\ ). mutating func removeRange(subRange: Range<Int>) } /// A type with a customized textual representation for debugging /// purposes. /// /// This textual representation is used when values are written to an /// *output stream* by `debugPrint` and `debugPrintln`, and is /// typically more verbose than the text provided by a `Printable`\ 's /// `description` property. /// /// In order to generate a textual representation for an instance of any /// type (which might or might not conform to `DebugPrintable`), use /// `toDebugString`. protocol DebugPrintable { /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } /// A hash-based mapping from `Key` to `Value` instances. Also a /// collection of key-value pairs with no defined ordering. struct Dictionary<Key : Hashable, Value> : CollectionType, DictionaryLiteralConvertible { typealias Element = (Key, Value) typealias Index = DictionaryIndex<Key, Value> /// Create an empty dictionary. init() /// Create a dictionary with at least the given number of /// elements worth of storage. The actual capacity will be the /// smallest power of 2 that's >= `minimumCapacity`. init(minimumCapacity: Int) /// The position of the first element in a non-empty dictionary. /// /// Identical to `endIndex` in an empty dictionary /// /// Complexity: amortized O(1) if `self` does not wrap a bridged /// `NSDictionary`, O(N) otherwise. var startIndex: DictionaryIndex<Key, Value> { get } /// 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()`. /// /// Complexity: amortized O(1) if `self` does not wrap a bridged /// `NSDictionary`, O(N) otherwise. var endIndex: DictionaryIndex<Key, Value> { get } /// Returns the `Index` for the given key, or `nil` if the key is not /// present in the dictionary. func indexForKey(key: Key) -> DictionaryIndex<Key, Value>? subscript (position: DictionaryIndex<Key, Value>) -> (Key, Value) { get } subscript (key: Key) -> Value? /// Update the value stored in the dictionary for the given key, or, if they /// key does not exist, add a new key-value pair to the dictionary. /// /// Returns the value that was replaced, or `nil` if a new key-value pair /// was added. mutating func updateValue(value: Value, forKey key: Key) -> Value? /// Remove the key-value pair at index `i` /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count`\ ). mutating func removeAtIndex(index: DictionaryIndex<Key, Value>) /// Remove a given key and the associated value from the dictionary. /// Returns the value that was removed, or `nil` if the key was not present /// in the dictionary. mutating func removeValueForKey(key: Key) -> Value? /// Remove all elements. /// /// Postcondition: `capacity == 0` if `keepCapacity` is `false`, otherwise /// the capacity will not be decreased. /// /// Invalidates all indices with respect to `self`. /// /// :param: keepCapacity If `true`, the operation preserves the /// storage capacity that the collection has, otherwise the underlying /// storage is released. The default is `false`. /// /// Complexity: O(\ `count`\ ). mutating func removeAll(keepCapacity: Bool) /// The number of entries in the dictionary. /// /// Complexity: O(1) var count: Int { get } /// Return a *generator* over the (key, value) pairs. /// /// Complexity: O(1) func generate() -> DictionaryGenerator<Key, Value> /// Create an instance initialized with `elements`. init(dictionaryLiteral elements: (Key, Value)...) /// True iff `count == 0` var isEmpty: Bool { get } /// A collection containing just the keys of `self` /// /// Keys appear in the same order as they occur as the `.0` member /// of key-value pairs in `self`. Each key in the result has a /// unique value. var keys: LazyForwardCollection<MapCollectionView<[Key : Value], Key>> { get } /// A collection containing just the values of `self` /// /// Values appear in the same order as they occur as the `.1` member /// of key-value pairs in `self`. var values: LazyForwardCollection<MapCollectionView<[Key : Value], Value>> { get } } extension Dictionary : Printable, DebugPrintable { /// A textual representation of `self`. var description: String { get } /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } extension Dictionary : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } /// A generator over the members of a `Dictionary<Key, Value>` struct DictionaryGenerator<Key : Hashable, Value> : GeneratorType { /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// Requires: no preceding call to `self.next()` has returned `nil`. mutating func next() -> (Key, Value)? } /// Used to access the key-value pairs in an instance of /// `Dictionary<Key, Value>`. /// /// Dictionary has two subscripting interfaces: /// /// 1. Subscripting with a key, yielding an optional value: /// /// v = d[k]! /// /// 2. Subscripting with an index, yielding a key-value pair: /// /// (k,v) = d[i] struct DictionaryIndex<Key : Hashable, Value> : ForwardIndexType, Comparable { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> DictionaryIndex<Key, Value> } /// Conforming types can be initialized with dictionary literals protocol DictionaryLiteralConvertible { typealias Key typealias Value /// Create an instance initialized with `elements`. init(dictionaryLiteral elements: (Key, Value)...) } struct Double { /// Create an instance initialized to zero. init() init(_bits v: Builtin.FPIEEE64) /// Create an instance initialized to `value`. init(_ value: Double) } extension Double : Printable { /// A textual representation of `self`. var description: String { get } } extension Double : FloatingPointType { /// The positive infinity. static var infinity: Double { get } /// A quiet NaN. static var NaN: Double { get } /// A quiet NaN. static var quietNaN: Double { get } /// `true` iff `self` is negative var isSignMinus: Bool { get } /// `true` iff `self` is normal (not zero, subnormal, infinity, or /// NaN). var isNormal: Bool { get } /// `true` iff `self` is zero, subnormal, or normal (not infinity /// or NaN). var isFinite: Bool { get } /// `true` iff `self` is +0.0 or -0.0. var isZero: Bool { get } /// `true` iff `self` is subnormal. var isSubnormal: Bool { get } /// `true` iff `self` is infinity. var isInfinite: Bool { get } /// `true` iff `self` is NaN. var isNaN: Bool { get } /// `true` iff `self` is a signaling NaN. var isSignaling: Bool { get } } extension Double { /// The IEEE 754 "class" of this type. var floatingPointClass: FloatingPointClassification { get } } extension Double : IntegerLiteralConvertible { init(_builtinIntegerLiteral value: Builtin.Int2048) /// Create an instance initialized to `value`. init(integerLiteral value: Int64) } extension Double { init(_builtinFloatLiteral value: Builtin.FPIEEE80) } extension Double : FloatLiteralConvertible { /// Create an instance initialized to `value`. init(floatLiteral value: Double) } extension Double : Comparable { } extension Double : Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } extension Double : AbsoluteValuable { /// Returns the absolute value of `x` static func abs(x: Double) -> Double } extension Double { init(_ v: UInt8) init(_ v: Int8) init(_ v: UInt16) init(_ v: Int16) init(_ v: UInt32) init(_ v: Int32) init(_ v: UInt64) init(_ v: Int64) init(_ v: UInt) init(_ v: Int) } extension Double { /// Construct an instance that approximates `other`. init(_ other: Float) /// Construct an instance that approximates `other`. init(_ other: Float80) } extension Double : Strideable { /// Returns a stride `x` such that `self.advancedBy(x)` approximates /// `other`. /// /// Complexity: O(1). func distanceTo(other: Double) -> Double /// Returns a `Self` `x` such that `self.distanceTo(x)` approximates /// `n`. /// /// Complexity: O(1). func advancedBy(amount: Double) -> Double } extension Double : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension Double : _CVarArgPassedAsDouble { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// A collection whose element type is `T` but that is always empty. struct EmptyCollection<T> : CollectionType { /// 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. typealias Index = Int /// Construct an instance. init() /// Always zero, just like `endIndex`. var startIndex: Index { get } /// Always zero, just like `startIndex`. var endIndex: Index { get } /// Returns an empty *generator*. /// /// Complexity: O(1) func generate() -> EmptyGenerator<T> subscript (position: Index) -> T { get } } extension EmptyCollection : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } /// A generator that never produces an element. /// /// See also: `EmptyCollection<T>`. struct EmptyGenerator<T> : GeneratorType, SequenceType { /// Construct an instance init() /// `EmptyGenerator` is also a `SequenceType`, so it `generate`\ 's /// a copy of itself func generate() -> EmptyGenerator<T> /// Return `nil`, indicating that there are no more elements. mutating func next() -> T? } /// The `GeneratorType` for `EnumerateSequence`. `EnumerateGenerator` /// wraps a `Base` `GeneratorType` and yields successive `Int` values, /// starting at zero, along with the elements of the underlying /// `Base`:: /// /// var g = EnumerateGenerator(["foo", "bar"].generate()) /// g.next() // (0, "foo") /// g.next() // (1, "bar") /// g.next() // nil /// /// Note:: idiomatic usage is to call `enumerate` instead of /// constructing an `EnumerateGenerator` directly. struct EnumerateGenerator<Base : GeneratorType> : GeneratorType, SequenceType { /// The type of element returned by `next()`. typealias Element = (index: Int, element: Base.Element) /// Construct from a `Base` generator init(_ base: Base) /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// Requires: no preceding call to `self.next()` has returned `nil`. mutating func next() -> Element? /// A type whose instances can produce the elements of this /// sequence, in order. typealias Generator = EnumerateGenerator<Base> /// `EnumerateGenerator` is also a `SequenceType`, so it /// `generate`\ s a copy of itself func generate() -> EnumerateGenerator<Base> } /// The `SequenceType` returned by `enumerate()`. `EnumerateSequence` /// is a sequence of pairs (*n*, *x*), where *n*\ s are consecutive /// `Int`\ s starting at zero, and *x*\ s are the elements of a `Base` /// `SequenceType`:: /// /// var s = EnumerateSequence(["foo", "bar"]) /// Array(s) // [(0, "foo"), (1, "bar")] /// /// Note:: idiomatic usage is to call `enumerate` instead of /// constructing an `EnumerateSequence` directly. struct EnumerateSequence<Base : SequenceType> : SequenceType { /// Construct from a `Base` sequence init(_ base: Base) /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> EnumerateGenerator<Base.Generator> } /// Instances of conforming types can be compared for value equality /// using operators `==` and `!=`. /// /// When adopting `Equatable`, only the `==` operator is required to be /// implemented. The standard library provides an implementation for `!=`. protocol Equatable { /// Return true if `lhs` is equal to `rhs`. /// /// **Equality implies substitutability**. When `x == y`, `x` and /// `y` are interchangeable in any code that only depends on their /// values. /// /// Class instance identity as distinguished by triple-equals `===` /// is notably not part of an instance's value. Exposing other /// non-value aspects of `Equatable` types is discouraged, and any /// that *are* exposed should be explicitly pointed out in /// documentation. /// /// **Equality is an equivalence relation** /// /// - `x == x` is `true` /// - `x == y` implies `y == x` /// - `x == y` and `y == z` implies `x == z` /// /// **Inequality is the inverse of equality**, i.e. `!(x == y)` iff /// `x != y` func ==(lhs: Self, rhs: Self) -> Bool } /// Conforming types can be initialized with string literals /// containing a single `Unicode extended grapheme cluster /// <http://www.unicode.org/glossary/#extended_grapheme_cluster>`_. protocol ExtendedGraphemeClusterLiteralConvertible : UnicodeScalarLiteralConvertible { typealias ExtendedGraphemeClusterLiteralType /// Create an instance initialized to `value`. init(extendedGraphemeClusterLiteral value: ExtendedGraphemeClusterLiteralType) } /// The default type for an otherwise-unconstrained unicode extended /// grapheme cluster literal typealias ExtendedGraphemeClusterType = String /// A collection type that can be efficiently appended-to. protocol ExtensibleCollectionType : _ExtensibleCollectionType { } /// A lazy `CollectionType` wrapper that includes the elements of an /// underlying collection that satisfy a predicate. Not /// automatically returned by `filter(x)` for two reasons: /// /// * The O(1) guarantee of our `Index` would be iffy at best, since /// it advances an underlying `Index` until the predicate is /// satisfied. Be aware that a `FilterCollectionView` may not offer /// the expected efficiency for this reason. /// /// * Constructing an `Array` from a `CollectionType` measures the length /// of the collection before traversing it to read the elements. /// This causes the filter predicate to be called twice for each /// element of the underlying collection, which is surprising. struct FilterCollectionView<Base : CollectionType> : CollectionType { /// 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. typealias Index = FilterCollectionViewIndex<Base> /// Construct an instance containing the elements of `base` that /// satisfy `predicate`. init(_ base: Base, includeElement predicate: (Base.Generator.Element) -> Bool) /// The position of the first element in a non-empty collection. /// /// Identical to `endIndex` in an empty collection. /// /// Complexity: O(N), where N is the ratio between unfiltered and /// filtered collection counts. var startIndex: FilterCollectionViewIndex<Base> { get } /// 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()`. /// /// Complexity: O(1) var endIndex: FilterCollectionViewIndex<Base> { get } subscript (position: FilterCollectionViewIndex<Base>) -> Base.Generator.Element { get } /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> FilterGenerator<Base.Generator> } /// The `Index` used for subscripting a `FilterCollectionView` struct FilterCollectionViewIndex<Base : CollectionType> : ForwardIndexType { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> FilterCollectionViewIndex<Base> } /// The `GeneratorType` used by `FilterSequenceView` and /// `FilterCollectionView` struct FilterGenerator<Base : GeneratorType> : GeneratorType, SequenceType { /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// Requires: `next()` has not been applied to a copy of `self` /// since the copy was made, and no preceding call to `self.next()` /// has returned `nil`. mutating func next() -> Base.Element? /// `FilterGenerator` is also a `SequenceType`, so it `generate`\ 's /// a copy of itself func generate() -> FilterGenerator<Base> } /// The lazy `SequenceType` returned by `filter(c)` where `c` is a /// `SequenceType` struct FilterSequenceView<Base : SequenceType> : SequenceType { /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> FilterGenerator<Base.Generator> } struct Float { /// Create an instance initialized to zero. init() init(_bits v: Builtin.FPIEEE32) /// Create an instance initialized to `value`. init(_ value: Float) } extension Float : Printable { /// A textual representation of `self`. var description: String { get } } extension Float : FloatingPointType { /// The positive infinity. static var infinity: Float { get } /// A quiet NaN. static var NaN: Float { get } /// A quiet NaN. static var quietNaN: Float { get } /// `true` iff `self` is negative var isSignMinus: Bool { get } /// `true` iff `self` is normal (not zero, subnormal, infinity, or /// NaN). var isNormal: Bool { get } /// `true` iff `self` is zero, subnormal, or normal (not infinity /// or NaN). var isFinite: Bool { get } /// `true` iff `self` is +0.0 or -0.0. var isZero: Bool { get } /// `true` iff `self` is subnormal. var isSubnormal: Bool { get } /// `true` iff `self` is infinity. var isInfinite: Bool { get } /// `true` iff `self` is NaN. var isNaN: Bool { get } /// `true` iff `self` is a signaling NaN. var isSignaling: Bool { get } } extension Float { /// The IEEE 754 "class" of this type. var floatingPointClass: FloatingPointClassification { get } } extension Float : IntegerLiteralConvertible { init(_builtinIntegerLiteral value: Builtin.Int2048) /// Create an instance initialized to `value`. init(integerLiteral value: Int64) } extension Float { init(_builtinFloatLiteral value: Builtin.FPIEEE80) } extension Float : FloatLiteralConvertible { /// Create an instance initialized to `value`. init(floatLiteral value: Float) } extension Float : Comparable { } extension Float : Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } extension Float : AbsoluteValuable { /// Returns the absolute value of `x` static func abs(x: Float) -> Float } extension Float { init(_ v: UInt8) init(_ v: Int8) init(_ v: UInt16) init(_ v: Int16) init(_ v: UInt32) init(_ v: Int32) init(_ v: UInt64) init(_ v: Int64) init(_ v: UInt) init(_ v: Int) } extension Float { /// Construct an instance that approximates `other`. init(_ other: Double) /// Construct an instance that approximates `other`. init(_ other: Float80) } extension Float : Strideable { /// Returns a stride `x` such that `self.advancedBy(x)` approximates /// `other`. /// /// Complexity: O(1). func distanceTo(other: Float) -> Float /// Returns a `Self` `x` such that `self.distanceTo(x)` approximates /// `n`. /// /// Complexity: O(1). func advancedBy(amount: Float) -> Float } extension Float : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension Float : _CVarArgPassedAsDouble { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// A 32-bit floating point type typealias Float32 = Float /// A 64-bit floating point type typealias Float64 = Double struct Float80 { /// Create an instance initialized to zero. init() init(_bits v: Builtin.FPIEEE80) /// Create an instance initialized to `value`. init(_ value: Float80) } extension Float80 : Printable { /// A textual representation of `self`. var description: String { get } } extension Float80 : IntegerLiteralConvertible { init(_builtinIntegerLiteral value: Builtin.Int2048) /// Create an instance initialized to `value`. init(integerLiteral value: Int64) } extension Float80 { init(_builtinFloatLiteral value: Builtin.FPIEEE80) } extension Float80 : FloatLiteralConvertible { /// Create an instance initialized to `value`. init(floatLiteral value: Float80) } extension Float80 : Comparable { } extension Float80 : Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } extension Float80 : AbsoluteValuable { /// Returns the absolute value of `x` static func abs(x: Float80) -> Float80 } extension Float80 { init(_ v: UInt8) init(_ v: Int8) init(_ v: UInt16) init(_ v: Int16) init(_ v: UInt32) init(_ v: Int32) init(_ v: UInt64) init(_ v: Int64) init(_ v: UInt) init(_ v: Int) } extension Float80 { /// Construct an instance that approximates `other`. init(_ other: Float) /// Construct an instance that approximates `other`. init(_ other: Double) } extension Float80 : Strideable { /// Returns a stride `x` such that `self.advancedBy(x)` approximates /// `other`. /// /// Complexity: O(1). func distanceTo(other: Float80) -> Float80 /// Returns a `Self` `x` such that `self.distanceTo(x)` approximates /// `n`. /// /// Complexity: O(1). func advancedBy(amount: Float80) -> Float80 } /// Conforming types can be initialized with floating point literals protocol FloatLiteralConvertible { typealias FloatLiteralType /// Create an instance initialized to `value`. init(floatLiteral value: FloatLiteralType) } /// The default type for an otherwise-unconstrained floating point literal typealias FloatLiteralType = Double /// The set of possible IEEE 754 "classes" enum FloatingPointClassification { case SignalingNaN case QuietNaN case NegativeInfinity case NegativeNormal case NegativeSubnormal case NegativeZero case PositiveZero case PositiveSubnormal case PositiveNormal case PositiveInfinity } extension FloatingPointClassification : Equatable { } /// A set of common requirements for Swift's floating point types. protocol FloatingPointType : Strideable { typealias _BitsType static func _fromBitPattern(bits: _BitsType) -> Self func _toBitPattern() -> _BitsType /// Create an instance initialized to `value`. init(_ value: UInt8) /// Create an instance initialized to `value`. init(_ value: Int8) /// Create an instance initialized to `value`. init(_ value: UInt16) /// Create an instance initialized to `value`. init(_ value: Int16) /// Create an instance initialized to `value`. init(_ value: UInt32) /// Create an instance initialized to `value`. init(_ value: Int32) /// Create an instance initialized to `value`. init(_ value: UInt64) /// Create an instance initialized to `value`. init(_ value: Int64) /// Create an instance initialized to `value`. init(_ value: UInt) /// Create an instance initialized to `value`. init(_ value: Int) /// The positive infinity. static var infinity: Self { get } /// A quiet NaN. static var NaN: Self { get } /// A quiet NaN. static var quietNaN: Self { get } /// @{ /// IEEE 754-2008 Non-computational operations. /// The IEEE 754 "class" of this type. var floatingPointClass: FloatingPointClassification { get } /// `true` iff `self` is negative var isSignMinus: Bool { get } /// `true` iff `self` is normal (not zero, subnormal, infinity, or /// NaN). var isNormal: Bool { get } /// `true` iff `self` is zero, subnormal, or normal (not infinity /// or NaN). var isFinite: Bool { get } /// `true` iff `self` is +0.0 or -0.0. var isZero: Bool { get } /// `true` iff `self` is subnormal. var isSubnormal: Bool { get } /// `true` iff `self` is infinity. var isInfinite: Bool { get } /// `true` iff `self` is NaN. var isNaN: Bool { get } /// `true` iff `self` is a signaling NaN. var isSignaling: Bool { get } } /// Represents a discrete value in a series, where a value's /// successor, if any, is reachable by applying the value's /// `successor()` method. protocol ForwardIndexType : _ForwardIndexType { } /// A type-erased generator. /// /// The generator for `SequenceOf<T>`. Forwards operations to an /// arbitrary underlying generator with the same `Element` type, /// hiding the specifics of the underlying generator type. /// /// See also: `SequenceOf<T>`. struct GeneratorOf<T> : GeneratorType, SequenceType { /// Construct an instance whose `next()` method calls `nextElement`. init(_ nextElement: () -> T?) /// Construct an instance whose `next()` method pulls its results /// from `base`. init<G : GeneratorType>(_ base: G) /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// Requires: `next()` has not been applied to a copy of `self` /// since the copy was made, and no preceding call to `self.next()` /// has returned `nil`. mutating func next() -> T? /// `GeneratorOf<T>` is also a `SequenceType`, so it `generate`\ s /// a copy of itself func generate() -> GeneratorOf<T> } /// A generator that produces one or fewer instances of `T`. struct GeneratorOfOne<T> : GeneratorType, SequenceType { /// Construct an instance that generates `element!`, or an empty /// sequence if `element == nil`. init(_ element: T?) /// `GeneratorOfOne` is also a `SequenceType`, so it `generate`\ s a /// copy of itself func generate() -> GeneratorOfOne<T> /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// Requires: `next()` has not been applied to a copy of `self` /// since the copy was made, and no preceding call to `self.next()` /// has returned `nil`. mutating func next() -> T? } /// A sequence built around a generator of type `G`. /// /// Useful mostly to recover the ability to use `for`\ ...\ `in`, /// given just a generator `g`:: /// /// for x in GeneratorSequence(g) { ... } struct GeneratorSequence<G : GeneratorType> : GeneratorType, SequenceType { /// Construct an instance whose generator is a copy of `base`. init(_ base: G) /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// Requires: `next()` has not been applied to a copy of `self` /// since the copy was made, and no preceding call to `self.next()` /// has returned `nil`. mutating func next() -> G.Element? /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> GeneratorSequence<G> } /// Encapsulates iteration state and interface for iteration over a /// *sequence*. /// /// **Note:** While it is safe to copy a *generator*, advancing one /// copy may invalidate the others. /// /// Any code that uses multiple generators (or `for`\ ...\ `in` loops) /// over a single *sequence* should have static knowledge that the /// specific *sequence* is multi-pass, either because its concrete /// type is known or because it is constrained to `CollectionType`. /// Also, the generators must be obtained by distinct calls to the /// *sequence's* `generate()` method, rather than by copying. protocol GeneratorType { /// The type of element generated by `self`. typealias Element /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// Requires: `next()` has not been applied to a copy of `self` /// since the copy was made, and no preceding call to `self.next()` /// has returned `nil`. Specific implementations of this protocol /// are encouraged to respond to violations of this requirement by /// calling `preconditionFailure("...")`. mutating func next() -> Element? } /// A half-open `IntervalType`, which contains its `start` but not its /// `end`. Can represent an empty interval. struct HalfOpenInterval<T : Comparable> : IntervalType, Equatable, Printable, DebugPrintable, Reflectable { /// The type of the `Interval`\ 's endpoints typealias Bound = T /// Construct a copy of `x` init(_ x: HalfOpenInterval<T>) /// Construct an interval with the given bounds. Requires: `start` /// <= `end`. init(_ start: T, _ end: T) /// The `Interval`\ 's lower bound. Invariant: `start` <= `end` var start: T { get } /// The `Interval`\ 's upper bound. Invariant: `start` <= `end` var end: T { get } /// A textual representation of `self`. var description: String { get } /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } /// Returns `true` iff the `Interval` contains `x` func contains(x: T) -> Bool /// Return `intervalToClamp` clamped to `self`. The bounds of the /// result, even if it is empty, are always limited to the bounds of /// `self` func clamp(intervalToClamp: HalfOpenInterval<T>) -> HalfOpenInterval<T> /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension HalfOpenInterval { /// `true` iff the `Interval` is empty. var isEmpty: Bool { get } } /// Instances of conforming types provide an integer `hashValue` and /// can be used as `Dictionary` keys. protocol Hashable : Equatable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } /// An optional type that allows implicit member access (via compiler /// magic). /// /// The compiler has special knowledge of the existence of /// ImplicitlyUnwrappedOptional<T>, but always interacts with it using the /// library intrinsics below. enum ImplicitlyUnwrappedOptional<T> : Reflectable, NilLiteralConvertible { case None case Some(T) /// Construct a `nil` instance. init() /// Construct a non-\ `nil` instance that stores `some`. init(_ some: T) /// Construct an instance from an explicitly unwrapped optional /// (`T?`). init(_ v: T?) /// Create an instance initialized with `nil`. init(nilLiteral: ()) /// If `self == nil`, returns `nil`. Otherwise, returns `f(self!)`. func map<U>(f: @noescape (T) -> U) -> U! /// Returns `f(self)!` iff `self` and `f(self)` are not nil. func flatMap<U>(f: @noescape (T) -> U!) -> U! /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension ImplicitlyUnwrappedOptional : Printable { /// A textual representation of `self`. var description: String { get } } extension ImplicitlyUnwrappedOptional : _ObjectiveCBridgeable { } /// A *generator* for an arbitrary *collection*. Provided `C` /// conforms to the other requirements of *CollectionType*, /// `IndexingGenerator<C>` can be used as the result of `C`\ 's /// `generate()` method. For example: /// /// .. parsed-literal:: /// /// struct MyCollection : CollectionType { /// struct Index : ForwardIndexType { *implementation hidden* } /// subscript(i: Index) -> MyElement { *implementation hidden* } /// func generate() -> **IndexingGenerator<MyCollection>** { /// return IndexingGenerator(self) /// } /// } struct IndexingGenerator<C : _CollectionType> : GeneratorType, SequenceType { /// Create a *generator* over the given collection init(_ seq: C) /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> IndexingGenerator<C> /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// Requires: no preceding call to `self.next()` has returned `nil`. mutating func next() -> C._Element? } /// A 64-bit signed integer value /// type. struct Int : SignedIntegerType { var value: Builtin.Int64 /// A type that can represent the number of steps between pairs of /// values. typealias Distance = Int /// Create an instance initialized to zero. init() init(_ v: Builtin.Word) /// Create an instance initialized to `value`. init(_ value: Int) /// Creates an integer from its big-endian representation, changing the /// byte order if necessary. init(bigEndian value: Int) /// Creates an integer from its little-endian representation, changing the /// byte order if necessary. init(littleEndian value: Int) init(_builtinIntegerLiteral value: Builtin.Int2048) /// Create an instance initialized to `value`. init(integerLiteral value: Int) /// Returns the big-endian representation of the integer, changing the /// byte order if necessary. var bigEndian: Int { get } /// Returns the little-endian representation of the integer, changing the /// byte order if necessary. var littleEndian: Int { get } /// Returns the current integer with the byte order swapped. var byteSwapped: Int { get } static var max: Int { get } static var min: Int { get } } extension Int : Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } extension Int : Printable { /// A textual representation of `self`. var description: String { get } } extension Int : RandomAccessIndexType { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> Int /// Returns the previous consecutive value before `self`. /// /// Requires: the previous value is representable. func predecessor() -> Int /// Return the minimum number of applications of `successor` or /// `predecessor` required to reach `other` from `self`. /// /// Complexity: O(1). func distanceTo(other: Int) -> Distance /// Return `self` offset by `n` steps. /// /// :returns: If `n > 0`, the result of applying `successor` to /// `self` `n` times. If `n < 0`, the result of applying /// `predecessor` to `self` `-n` times. Otherwise, `self`. /// /// Complexity: O(1) func advancedBy(amount: Distance) -> Int } extension Int { /// Add `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func addWithOverflow(lhs: Int, _ rhs: Int) -> (Int, overflow: Bool) /// Subtract `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func subtractWithOverflow(lhs: Int, _ rhs: Int) -> (Int, overflow: Bool) /// Multiply `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func multiplyWithOverflow(lhs: Int, _ rhs: Int) -> (Int, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// a result and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func divideWithOverflow(lhs: Int, _ rhs: Int) -> (Int, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// the remainder and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func remainderWithOverflow(lhs: Int, _ rhs: Int) -> (Int, overflow: Bool) /// Represent this number using Swift's widest native signed /// integer type. func toIntMax() -> IntMax } extension Int : SignedNumberType { } extension Int { init(_ v: UInt8) init(_ v: Int8) init(_ v: UInt16) init(_ v: Int16) init(_ v: UInt32) init(_ v: Int32) init(_ v: UInt64) /// Construct a `Int` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt64) init(_ v: Int64) /// Construct a `Int` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int64) init(_ v: UInt) /// Construct a `Int` having the same memory representation as /// the `UInt` `bitPattern`. No range or overflow checking /// occurs, and the resulting `Int` may not have the same numeric /// value as `bitPattern`--it is only guaranteed to use the same /// pattern of bits. init(bitPattern: UInt) } extension Int : BitwiseOperationsType { /// The empty bitset of type Int. static var allZeros: Int { get } } extension Int { /// Construct an instance that approximates `other`. init(_ other: Float) /// Construct an instance that approximates `other`. init(_ other: Double) /// Construct an instance that approximates `other`. init(_ other: Float80) } extension Int : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension Int : CVarArgType { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// A 16-bit signed integer value /// type. struct Int16 : SignedIntegerType { var value: Builtin.Int16 /// A type that can represent the number of steps between pairs of /// values. typealias Distance = Int /// Create an instance initialized to zero. init() /// Create an instance initialized to `value`. init(_ value: Int16) /// Creates an integer from its big-endian representation, changing the /// byte order if necessary. init(bigEndian value: Int16) /// Creates an integer from its little-endian representation, changing the /// byte order if necessary. init(littleEndian value: Int16) init(_builtinIntegerLiteral value: Builtin.Int2048) /// Create an instance initialized to `value`. init(integerLiteral value: Int16) /// Returns the big-endian representation of the integer, changing the /// byte order if necessary. var bigEndian: Int16 { get } /// Returns the little-endian representation of the integer, changing the /// byte order if necessary. var littleEndian: Int16 { get } /// Returns the current integer with the byte order swapped. var byteSwapped: Int16 { get } static var max: Int16 { get } static var min: Int16 { get } } extension Int16 : Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } extension Int16 : Printable { /// A textual representation of `self`. var description: String { get } } extension Int16 : RandomAccessIndexType { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> Int16 /// Returns the previous consecutive value before `self`. /// /// Requires: the previous value is representable. func predecessor() -> Int16 /// Return the minimum number of applications of `successor` or /// `predecessor` required to reach `other` from `self`. /// /// Complexity: O(1). func distanceTo(other: Int16) -> Distance /// Return `self` offset by `n` steps. /// /// :returns: If `n > 0`, the result of applying `successor` to /// `self` `n` times. If `n < 0`, the result of applying /// `predecessor` to `self` `-n` times. Otherwise, `self`. /// /// Complexity: O(1) func advancedBy(amount: Distance) -> Int16 } extension Int16 { /// Add `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func addWithOverflow(lhs: Int16, _ rhs: Int16) -> (Int16, overflow: Bool) /// Subtract `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func subtractWithOverflow(lhs: Int16, _ rhs: Int16) -> (Int16, overflow: Bool) /// Multiply `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func multiplyWithOverflow(lhs: Int16, _ rhs: Int16) -> (Int16, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// a result and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func divideWithOverflow(lhs: Int16, _ rhs: Int16) -> (Int16, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// the remainder and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func remainderWithOverflow(lhs: Int16, _ rhs: Int16) -> (Int16, overflow: Bool) /// Represent this number using Swift's widest native signed /// integer type. func toIntMax() -> IntMax } extension Int16 : SignedNumberType { } extension Int16 { init(_ v: UInt8) init(_ v: Int8) init(_ v: UInt16) init(_ v: UInt32) /// Construct a `Int16` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt32) init(_ v: Int32) /// Construct a `Int16` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int32) init(_ v: UInt64) /// Construct a `Int16` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt64) init(_ v: Int64) /// Construct a `Int16` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int64) init(_ v: UInt) /// Construct a `Int16` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt) init(_ v: Int) /// Construct a `Int16` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int) /// Construct a `Int16` having the same memory representation as /// the `UInt16` `bitPattern`. No range or overflow checking /// occurs, and the resulting `Int16` may not have the same numeric /// value as `bitPattern`--it is only guaranteed to use the same /// pattern of bits. init(bitPattern: UInt16) } extension Int16 : BitwiseOperationsType { /// The empty bitset of type Int16. static var allZeros: Int16 { get } } extension Int16 { /// Construct an instance that approximates `other`. init(_ other: Float) /// Construct an instance that approximates `other`. init(_ other: Double) /// Construct an instance that approximates `other`. init(_ other: Float80) } extension Int16 : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension Int16 : CVarArgType { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// A 32-bit signed integer value /// type. struct Int32 : SignedIntegerType { var value: Builtin.Int32 /// A type that can represent the number of steps between pairs of /// values. typealias Distance = Int /// Create an instance initialized to zero. init() /// Create an instance initialized to `value`. init(_ value: Int32) /// Creates an integer from its big-endian representation, changing the /// byte order if necessary. init(bigEndian value: Int32) /// Creates an integer from its little-endian representation, changing the /// byte order if necessary. init(littleEndian value: Int32) init(_builtinIntegerLiteral value: Builtin.Int2048) /// Create an instance initialized to `value`. init(integerLiteral value: Int32) /// Returns the big-endian representation of the integer, changing the /// byte order if necessary. var bigEndian: Int32 { get } /// Returns the little-endian representation of the integer, changing the /// byte order if necessary. var littleEndian: Int32 { get } /// Returns the current integer with the byte order swapped. var byteSwapped: Int32 { get } static var max: Int32 { get } static var min: Int32 { get } } extension Int32 : Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } extension Int32 : Printable { /// A textual representation of `self`. var description: String { get } } extension Int32 : RandomAccessIndexType { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> Int32 /// Returns the previous consecutive value before `self`. /// /// Requires: the previous value is representable. func predecessor() -> Int32 /// Return the minimum number of applications of `successor` or /// `predecessor` required to reach `other` from `self`. /// /// Complexity: O(1). func distanceTo(other: Int32) -> Distance /// Return `self` offset by `n` steps. /// /// :returns: If `n > 0`, the result of applying `successor` to /// `self` `n` times. If `n < 0`, the result of applying /// `predecessor` to `self` `-n` times. Otherwise, `self`. /// /// Complexity: O(1) func advancedBy(amount: Distance) -> Int32 } extension Int32 { /// Add `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func addWithOverflow(lhs: Int32, _ rhs: Int32) -> (Int32, overflow: Bool) /// Subtract `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func subtractWithOverflow(lhs: Int32, _ rhs: Int32) -> (Int32, overflow: Bool) /// Multiply `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func multiplyWithOverflow(lhs: Int32, _ rhs: Int32) -> (Int32, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// a result and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func divideWithOverflow(lhs: Int32, _ rhs: Int32) -> (Int32, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// the remainder and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func remainderWithOverflow(lhs: Int32, _ rhs: Int32) -> (Int32, overflow: Bool) /// Represent this number using Swift's widest native signed /// integer type. func toIntMax() -> IntMax } extension Int32 : SignedNumberType { } extension Int32 { init(_ v: UInt8) init(_ v: Int8) init(_ v: UInt16) init(_ v: Int16) init(_ v: UInt32) init(_ v: UInt64) /// Construct a `Int32` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt64) init(_ v: Int64) /// Construct a `Int32` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int64) init(_ v: UInt) /// Construct a `Int32` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt) init(_ v: Int) /// Construct a `Int32` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int) /// Construct a `Int32` having the same memory representation as /// the `UInt32` `bitPattern`. No range or overflow checking /// occurs, and the resulting `Int32` may not have the same numeric /// value as `bitPattern`--it is only guaranteed to use the same /// pattern of bits. init(bitPattern: UInt32) } extension Int32 : BitwiseOperationsType { /// The empty bitset of type Int32. static var allZeros: Int32 { get } } extension Int32 { /// Construct an instance that approximates `other`. init(_ other: Float) /// Construct an instance that approximates `other`. init(_ other: Double) /// Construct an instance that approximates `other`. init(_ other: Float80) } extension Int32 : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension Int32 : CVarArgType { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// A 64-bit signed integer value /// type. struct Int64 : SignedIntegerType { var value: Builtin.Int64 /// A type that can represent the number of steps between pairs of /// values. typealias Distance = Int /// Create an instance initialized to zero. init() /// Create an instance initialized to `value`. init(_ value: Int64) /// Creates an integer from its big-endian representation, changing the /// byte order if necessary. init(bigEndian value: Int64) /// Creates an integer from its little-endian representation, changing the /// byte order if necessary. init(littleEndian value: Int64) init(_builtinIntegerLiteral value: Builtin.Int2048) /// Create an instance initialized to `value`. init(integerLiteral value: Int64) /// Returns the big-endian representation of the integer, changing the /// byte order if necessary. var bigEndian: Int64 { get } /// Returns the little-endian representation of the integer, changing the /// byte order if necessary. var littleEndian: Int64 { get } /// Returns the current integer with the byte order swapped. var byteSwapped: Int64 { get } static var max: Int64 { get } static var min: Int64 { get } } extension Int64 : Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } extension Int64 : Printable { /// A textual representation of `self`. var description: String { get } } extension Int64 : RandomAccessIndexType { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> Int64 /// Returns the previous consecutive value before `self`. /// /// Requires: the previous value is representable. func predecessor() -> Int64 /// Return the minimum number of applications of `successor` or /// `predecessor` required to reach `other` from `self`. /// /// Complexity: O(1). func distanceTo(other: Int64) -> Distance /// Return `self` offset by `n` steps. /// /// :returns: If `n > 0`, the result of applying `successor` to /// `self` `n` times. If `n < 0`, the result of applying /// `predecessor` to `self` `-n` times. Otherwise, `self`. /// /// Complexity: O(1) func advancedBy(amount: Distance) -> Int64 } extension Int64 { /// Add `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func addWithOverflow(lhs: Int64, _ rhs: Int64) -> (Int64, overflow: Bool) /// Subtract `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func subtractWithOverflow(lhs: Int64, _ rhs: Int64) -> (Int64, overflow: Bool) /// Multiply `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func multiplyWithOverflow(lhs: Int64, _ rhs: Int64) -> (Int64, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// a result and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func divideWithOverflow(lhs: Int64, _ rhs: Int64) -> (Int64, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// the remainder and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func remainderWithOverflow(lhs: Int64, _ rhs: Int64) -> (Int64, overflow: Bool) /// Represent this number using Swift's widest native signed /// integer type. func toIntMax() -> IntMax } extension Int64 : SignedNumberType { } extension Int64 { init(_ v: UInt8) init(_ v: Int8) init(_ v: UInt16) init(_ v: Int16) init(_ v: UInt32) init(_ v: Int32) init(_ v: UInt64) init(_ v: UInt) init(_ v: Int) /// Construct a `Int64` having the same memory representation as /// the `UInt64` `bitPattern`. No range or overflow checking /// occurs, and the resulting `Int64` may not have the same numeric /// value as `bitPattern`--it is only guaranteed to use the same /// pattern of bits. init(bitPattern: UInt64) } extension Int64 : BitwiseOperationsType { /// The empty bitset of type Int64. static var allZeros: Int64 { get } } extension Int64 { /// Construct an instance that approximates `other`. init(_ other: Float) /// Construct an instance that approximates `other`. init(_ other: Double) /// Construct an instance that approximates `other`. init(_ other: Float80) } extension Int64 : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension Int64 : CVarArgType { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// A 8-bit signed integer value /// type. struct Int8 : SignedIntegerType { var value: Builtin.Int8 /// A type that can represent the number of steps between pairs of /// values. typealias Distance = Int /// Create an instance initialized to zero. init() /// Create an instance initialized to `value`. init(_ value: Int8) init(_builtinIntegerLiteral value: Builtin.Int2048) /// Create an instance initialized to `value`. init(integerLiteral value: Int8) static var max: Int8 { get } static var min: Int8 { get } } extension Int8 : Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } extension Int8 : Printable { /// A textual representation of `self`. var description: String { get } } extension Int8 : RandomAccessIndexType { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> Int8 /// Returns the previous consecutive value before `self`. /// /// Requires: the previous value is representable. func predecessor() -> Int8 /// Return the minimum number of applications of `successor` or /// `predecessor` required to reach `other` from `self`. /// /// Complexity: O(1). func distanceTo(other: Int8) -> Distance /// Return `self` offset by `n` steps. /// /// :returns: If `n > 0`, the result of applying `successor` to /// `self` `n` times. If `n < 0`, the result of applying /// `predecessor` to `self` `-n` times. Otherwise, `self`. /// /// Complexity: O(1) func advancedBy(amount: Distance) -> Int8 } extension Int8 { /// Add `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func addWithOverflow(lhs: Int8, _ rhs: Int8) -> (Int8, overflow: Bool) /// Subtract `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func subtractWithOverflow(lhs: Int8, _ rhs: Int8) -> (Int8, overflow: Bool) /// Multiply `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func multiplyWithOverflow(lhs: Int8, _ rhs: Int8) -> (Int8, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// a result and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func divideWithOverflow(lhs: Int8, _ rhs: Int8) -> (Int8, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// the remainder and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func remainderWithOverflow(lhs: Int8, _ rhs: Int8) -> (Int8, overflow: Bool) /// Represent this number using Swift's widest native signed /// integer type. func toIntMax() -> IntMax } extension Int8 : SignedNumberType { } extension Int8 { init(_ v: UInt8) init(_ v: UInt16) /// Construct a `Int8` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt16) init(_ v: Int16) /// Construct a `Int8` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int16) init(_ v: UInt32) /// Construct a `Int8` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt32) init(_ v: Int32) /// Construct a `Int8` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int32) init(_ v: UInt64) /// Construct a `Int8` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt64) init(_ v: Int64) /// Construct a `Int8` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int64) init(_ v: UInt) /// Construct a `Int8` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt) init(_ v: Int) /// Construct a `Int8` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int) /// Construct a `Int8` having the same memory representation as /// the `UInt8` `bitPattern`. No range or overflow checking /// occurs, and the resulting `Int8` may not have the same numeric /// value as `bitPattern`--it is only guaranteed to use the same /// pattern of bits. init(bitPattern: UInt8) } extension Int8 : BitwiseOperationsType { /// The empty bitset of type Int8. static var allZeros: Int8 { get } } extension Int8 { /// Construct an instance that approximates `other`. init(_ other: Float) /// Construct an instance that approximates `other`. init(_ other: Double) /// Construct an instance that approximates `other`. init(_ other: Float80) } extension Int8 : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension Int8 : CVarArgType { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// The largest native signed integer type typealias IntMax = Int64 /// The common requirements for types that support integer arithmetic. protocol IntegerArithmeticType : _IntegerArithmeticType, Comparable { /// Add `lhs` and `rhs`, returning a result and trapping in case of /// arithmetic overflow (except in -Ounchecked builds). func +(lhs: Self, rhs: Self) -> Self /// Subtract `lhs` and `rhs`, returning a result and trapping in case of /// arithmetic overflow (except in -Ounchecked builds). func -(lhs: Self, rhs: Self) -> Self /// Multiply `lhs` and `rhs`, returning a result and trapping in case of /// arithmetic overflow (except in -Ounchecked builds). func *(lhs: Self, rhs: Self) -> Self /// Divide `lhs` and `rhs`, returning a result and trapping in case of /// arithmetic overflow (except in -Ounchecked builds). func /(lhs: Self, rhs: Self) -> Self /// Divide `lhs` and `rhs`, returning the remainder and trapping in case of /// arithmetic overflow (except in -Ounchecked builds). func %(lhs: Self, rhs: Self) -> Self /// Explicitly convert to `IntMax`, trapping on overflow (except in /// -Ounchecked builds). func toIntMax() -> IntMax } /// Conforming types can be initialized with integer literals protocol IntegerLiteralConvertible { typealias IntegerLiteralType /// Create an instance initialized to `value`. init(integerLiteral value: IntegerLiteralType) } /// The default type for an otherwise-unconstrained integer literal typealias IntegerLiteralType = Int /// A set of common requirements for Swift's integer types. protocol IntegerType : _IntegerType, RandomAccessIndexType { } /// An interval over a `Comparable` type. protocol IntervalType { /// The type of the `Interval`\ 's endpoints typealias Bound : Comparable /// Returns `true` iff the interval contains `value` func contains(value: Bound) -> Bool /// Return `rhs` clamped to `self`. The bounds of the result, even /// if it is empty, are always within the bounds of `self` func clamp(intervalToClamp: Self) -> Self /// True iff `self` is empty var isEmpty: Bool { get } /// The `Interval`\ 's lower bound. Invariant: `start` <= `end` var start: Bound { get } /// The `Interval`\ 's upper bound. Invariant: `start` <= `end` var end: Bound { get } } /// A collection that forwards its implementation to an underlying /// collection instance while exposing lazy computations as methods. struct LazyBidirectionalCollection<S : CollectionType where S.Index : BidirectionalIndexType> : CollectionType { /// Construct an instance with `base` as its underlying collection /// instance. init(_ base: S) /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> S.Generator /// The position of the first element in a non-empty collection. /// /// Identical to `endIndex` in an empty collection. var startIndex: S.Index { get } /// 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()`. var endIndex: S.Index { get } /// True if and only if the collection is empty var isEmpty: Bool { get } /// The first element, or `nil` if `self` is empty var first: S.Generator.Element? { get } /// The last element, or `nil` if `self` is empty var last: S.Generator.Element? { get } subscript (position: S.Index) -> S.Generator.Element { get } /// an Array, created on-demand, containing the elements of this /// lazy CollectionType. var array: [S.Generator.Element] { get } } extension LazyBidirectionalCollection { /// Return a lazy SequenceType containing the elements `x` of `source` for /// which `includeElement(x)` is `true` func filter(includeElement: (S.Generator.Element) -> Bool) -> LazySequence<FilterSequenceView<S>> } extension LazyBidirectionalCollection { /// Return a `MapCollectionView` over this `LazyBidirectionalCollection`. The elements of /// the result are computed lazily, each time they are read, by /// calling `transform` function on a base element. func map<U>(transform: (S.Generator.Element) -> U) -> LazyBidirectionalCollection<MapCollectionView<S, U>> } extension LazyBidirectionalCollection { /// Return a `BidirectionalReverseView` over this `LazyBidirectionalCollection`. The elements of /// the result are computed lazily, each time they are read, by /// calling `transform` function on a base element. func reverse() -> LazyBidirectionalCollection<BidirectionalReverseView<S>> } /// A collection that forwards its implementation to an underlying /// collection instance while exposing lazy computations as methods. struct LazyForwardCollection<S : CollectionType where S.Index : ForwardIndexType> : CollectionType { /// Construct an instance with `base` as its underlying collection /// instance. init(_ base: S) /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> S.Generator /// The position of the first element in a non-empty collection. /// /// Identical to `endIndex` in an empty collection. var startIndex: S.Index { get } /// 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()`. var endIndex: S.Index { get } /// True if and only if the collection is empty var isEmpty: Bool { get } /// The first element, or `nil` if `self` is empty var first: S.Generator.Element? { get } subscript (position: S.Index) -> S.Generator.Element { get } /// an Array, created on-demand, containing the elements of this /// lazy CollectionType. var array: [S.Generator.Element] { get } } extension LazyForwardCollection { /// Return a lazy SequenceType containing the elements `x` of `source` for /// which `includeElement(x)` is `true` func filter(includeElement: (S.Generator.Element) -> Bool) -> LazySequence<FilterSequenceView<S>> } extension LazyForwardCollection { /// Return a `MapCollectionView` over this `LazyForwardCollection`. The elements of /// the result are computed lazily, each time they are read, by /// calling `transform` function on a base element. func map<U>(transform: (S.Generator.Element) -> U) -> LazyForwardCollection<MapCollectionView<S, U>> } /// A collection that forwards its implementation to an underlying /// collection instance while exposing lazy computations as methods. struct LazyRandomAccessCollection<S : CollectionType where S.Index : RandomAccessIndexType> : CollectionType { /// Construct an instance with `base` as its underlying collection /// instance. init(_ base: S) /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> S.Generator /// The position of the first element in a non-empty collection. /// /// Identical to `endIndex` in an empty collection. var startIndex: S.Index { get } /// 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()`. var endIndex: S.Index { get } /// True if and only if the collection is empty var isEmpty: Bool { get } /// The first element, or `nil` if `self` is empty var first: S.Generator.Element? { get } /// The last element, or `nil` if `self` is empty var last: S.Generator.Element? { get } subscript (position: S.Index) -> S.Generator.Element { get } /// an Array, created on-demand, containing the elements of this /// lazy CollectionType. var array: [S.Generator.Element] { get } } extension LazyRandomAccessCollection { /// Return a lazy SequenceType containing the elements `x` of `source` for /// which `includeElement(x)` is `true` func filter(includeElement: (S.Generator.Element) -> Bool) -> LazySequence<FilterSequenceView<S>> } extension LazyRandomAccessCollection { /// Return a `MapCollectionView` over this `LazyRandomAccessCollection`. The elements of /// the result are computed lazily, each time they are read, by /// calling `transform` function on a base element. func map<U>(transform: (S.Generator.Element) -> U) -> LazyRandomAccessCollection<MapCollectionView<S, U>> } extension LazyRandomAccessCollection { /// Return a `RandomAccessReverseView` over this `LazyRandomAccessCollection`. The elements of /// the result are computed lazily, each time they are read, by /// calling `transform` function on a base element. func reverse() -> LazyBidirectionalCollection<RandomAccessReverseView<S>> } /// A sequence that forwards its implementation to an underlying /// sequence instance while exposing lazy computations as methods. struct LazySequence<S : SequenceType> : SequenceType { /// Construct an instance with `base` as its underlying sequence /// instance. init(_ base: S) /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> S.Generator /// an Array, created on-demand, containing the elements of this /// lazy SequenceType. var array: [S.Generator.Element] { get } } extension LazySequence { /// Return a lazy SequenceType containing the elements `x` of `source` for /// which `includeElement(x)` is `true` func filter(includeElement: (S.Generator.Element) -> Bool) -> LazySequence<FilterSequenceView<S>> } extension LazySequence { /// Return a `MapSequenceView` over this `LazySequence`. The elements of /// the result are computed lazily, each time they are read, by /// calling `transform` function on a base element. func map<U>(transform: (S.Generator.Element) -> U) -> LazySequence<MapSequenceView<S, U>> } /// A class whose instances contain a property of type `Value` and raw /// storage for an array of `Element`, whose size is determined at /// instance creation. /// /// Note that the `Element` array is suitably-aligned **raw memory**. /// You are expected to construct and---if necessary---destroy objects /// there yourself, using the APIs on `UnsafeMutablePointer<Element>`. /// Typical usage stores a count and capacity in `Value` and destroys /// any live elements in the `deinit` of a subclass. Note: subclasses /// must not have any stored properties; any storage needed should be /// included in `Value`. class ManagedBuffer<Value, Element> : ManagedProtoBuffer<Value, Element> { /// Create a new instance of the most-derived class, calling /// `initializeValue` on the partially-constructed object to /// generate an initial `Value`. final class func create(minimumCapacity: Int, initialValue: (ManagedProtoBuffer<Value, Element>) -> Value) -> ManagedBuffer<Value, Element> /// Destroy the stored Value deinit /// The stored `Value` instance. final var value: Value } /// Contains a buffer object, and provides access to an instance of /// `Value` and contiguous storage for an arbitrary number of /// `Element` instances stored in that buffer. /// /// For most purposes, the `ManagedBuffer` class works fine for this /// purpose, and can simply be used on its own. However, in cases /// where objects of various different classes must serve as storage, /// `ManagedBufferPointer` is needed. /// /// A valid buffer class is non-`@objc`, with no declared stored /// properties. Its `deinit` must destroy its /// stored `Value` and any constructed `Element`\ s. /// /// Example Buffer Class /// -------------------- /// /// :: /// /// class MyBuffer<Element> { // non-@objc /// typealias Manager = ManagedBufferPointer<(Int,String), Element> /// deinit { /// Manager(unsafeBufferObject: self).withUnsafeMutablePointers { /// (pointerToValue, pointerToElements)->Void in /// pointerToElements.destroy(self.count) /// pointerToValue.destroy() /// } /// } /// /// // All properties are *computed* based on members of the Value /// var count: Int { /// return Manager(unsafeBufferObject: self).value.0 /// } /// var name: String { /// return Manager(unsafeBufferObject: self).value.1 /// } /// } /// struct ManagedBufferPointer<Value, Element> : Equatable { /// Create with new storage containing an initial `Value` and space /// for at least `minimumCapacity` `element`\ s. /// /// :param: `bufferClass` the class of the object used for storage. /// :param: `minimumCapacity` the minimum number of `Element`\ s that /// must be able to be stored in the new buffer. /// :param: `initialValue` a function that produces the initial /// `Value` instance stored in the buffer, given the `buffer` /// object and a function that can be called on it to get the actual /// number of allocated elements. /// /// Requires: minimumCapacity >= 0, and the type indicated by /// `bufferClass` is a non-`@objc` class with no declared stored /// properties. The `deinit` of `bufferClass` must destroy its /// stored `Value` and any constructed `Element`\ s. init(bufferClass: AnyClass, minimumCapacity: Int, initialValue: (buffer: AnyObject, allocatedCount: (AnyObject) -> Int) -> Value) /// Manage the given `buffer`. /// /// Requires: `buffer` is an instance of a non-`@objc` class whose /// `deinit` destroys its stored `Value` and any constructed /// `Element`\ s. init(unsafeBufferObject buffer: AnyObject) /// The stored `Value` instance. var value: Value /// Return the object instance being used for storage. var buffer: AnyObject { get } /// The actual number of elements that can be stored in this object. /// /// This value may be nontrivial to compute; it is usually a good /// idea to store this information in the "value" area when /// an instance is created. var allocatedElementCount: Int { get } /// Call `body` with an `UnsafeMutablePointer` to the stored /// `Value`. **Note**: this pointer is only valid /// for the duration of the call to `body` func withUnsafeMutablePointerToValue<R>(body: (UnsafeMutablePointer<Value>) -> R) -> R /// Call `body` with an `UnsafeMutablePointer` to the `Element` /// storage. **Note**: this pointer is only valid /// for the duration of the call to `body`. func withUnsafeMutablePointerToElements<R>(body: (UnsafeMutablePointer<Element>) -> R) -> R /// Call `body` with `UnsafeMutablePointer`\ s to the stored `Value` /// and raw `Element` storage. **Note**: these pointers are only valid /// for the duration of the call to `body`. func withUnsafeMutablePointers<R>(body: (UnsafeMutablePointer<Value>, UnsafeMutablePointer<Element>) -> R) -> R /// Returns true iff `self` holds the only strong reference to its buffer. /// /// See `isUniquelyReferenced` for details. mutating func holdsUniqueReference() -> Bool /// Returns true iff either `self` holds the only strong reference /// to its buffer or the pinned has been 'pinned'. /// /// See `isUniquelyReferenced` for details. mutating func holdsUniqueOrPinnedReference() -> Bool } /// A base class of `ManagedBuffer<Value,Element>`, used during /// instance creation. /// /// During instance creation, in particular during /// `ManagedBuffer.create`\ 's call to initialize, `ManagedBuffer`\ 's /// `value` property is as-yet uninitialized, and therefore /// `ManagedProtoBuffer` does not offer access to the as-yet /// uninitialized `value` property of `ManagedBuffer`. class ManagedProtoBuffer<Value, Element> : NonObjectiveCBase { /// The actual number of elements that can be stored in this object. /// /// This value may be nontrivial to compute; it is usually a good /// idea to store this information in the "value" area when /// an instance is created. final var allocatedElementCount: Int { get } /// Call `body` with an `UnsafeMutablePointer` to the stored /// `Value`. **Note**: this pointer is only valid /// for the duration of the call to `body`. final func withUnsafeMutablePointerToValue<R>(body: (UnsafeMutablePointer<Value>) -> R) -> R /// Call `body` with an `UnsafeMutablePointer` to the `Element` /// storage. **Note**: this pointer is only valid /// for the duration of the call to `body`. final func withUnsafeMutablePointerToElements<R>(body: (UnsafeMutablePointer<Element>) -> R) -> R /// Call `body` with `UnsafeMutablePointer`\ s to the stored `Value` /// and raw `Element` storage. **Note**: these pointers are only valid /// for the duration of the call to `body`. final func withUnsafeMutablePointers<R>(body: (UnsafeMutablePointer<Value>, UnsafeMutablePointer<Element>) -> R) -> R } /// A `CollectionType` whose elements consist of those in a `Base` /// `CollectionType` passed through a transform function returning `T`. /// These elements are computed lazily, each time they're read, by /// calling the transform function on a base element. struct MapCollectionView<Base : CollectionType, T> : CollectionType { /// The position of the first element in a non-empty collection. /// /// Identical to `endIndex` in an empty collection. var startIndex: Base.Index { get } /// 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()`. var endIndex: Base.Index { get } subscript (position: Base.Index) -> T { get } /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> MapSequenceGenerator<Base.Generator, T> } /// The `GeneratorType` used by `MapSequenceView` and `MapCollectionView`. /// Produces each element by passing the output of the `Base` /// `GeneratorType` through a transform function returning `T` struct MapSequenceGenerator<Base : GeneratorType, T> : GeneratorType, SequenceType { /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// Requires: `next()` has not been applied to a copy of `self` /// since the copy was made, and no preceding call to `self.next()` /// has returned `nil`. mutating func next() -> T? /// `MapSequenceGenerator` is also a `SequenceType`, so it /// `generate`\ 's a copy of itself func generate() -> MapSequenceGenerator<Base, T> } /// A `SequenceType` whose elements consist of those in a `Base` /// `SequenceType` passed through a transform function returning `T`. /// These elements are computed lazily, each time they're read, by /// calling the transform function on a base element. struct MapSequenceView<Base : SequenceType, T> : SequenceType { /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> MapSequenceGenerator<Base.Generator, T> } /// How children of this value should be presented in the IDE. enum MirrorDisposition { case Struct case Class case Enum case Tuple case Aggregate case IndexContainer case KeyContainer case MembershipContainer case Container case Optional case ObjCObject } /// The type returned by `reflect(x)`; supplies an API for runtime /// reflection on `x` protocol MirrorType { /// The instance being reflected var value: Any { get } /// Identical to `value.dynamicType` var valueType: Any.Type { get } /// A unique identifier for `value` if it is a class instance; `nil` /// otherwise. var objectIdentifier: ObjectIdentifier? { get } /// The count of `value`\ 's logical children var count: Int { get } subscript (i: Int) -> (String, MirrorType) { get } /// A string description of `value`. var summary: String { get } /// A rich representation of `value` for an IDE, or `nil` if none is supplied. var quickLookObject: QuickLookObject? { get } /// How `value` should be presented in an IDE. var disposition: MirrorDisposition { get } } /// A *collection* that supports subscript assignment. /// /// For any instance `a` of a type conforming to /// `MutableCollectionType`, :: /// /// a[i] = x /// let y = a[i] /// /// is equivalent to :: /// /// a[i] = x /// let y = x /// protocol MutableCollectionType : CollectionType { subscript (position: Self.Index) -> Self.Generator.Element { get set } } /// A *collection* with mutable slices. /// /// For example, /// /// .. parsed-literal: /// /// x[i..<j] = *someExpression* /// x[i..<j].\ *mutatingMethod*\ () protocol MutableSliceable : Sliceable, MutableCollectionType { subscript (_: Range<Self.Index>) -> Self.SubSlice { get set } } /// Conforming types can be initialized with `nil`. protocol NilLiteralConvertible { /// Create an instance initialized with `nil`. init(nilLiteral: ()) } /// A common base class for classes that need to be non-\ `@objc`, /// recognizably in the type system. /// /// See `isUniquelyReferenced` class NonObjectiveCBase { } /// A unique identifier for a class instance or metatype. This can be used by /// reflection clients to recognize cycles in the object graph. /// /// In Swift, only class instances and metatypes have unique identities. There /// is no notion of identity for structs, enums, functions, or tuples. struct ObjectIdentifier : Hashable, Comparable { /// Convert to a `UInt` that captures the full value of `self`. /// /// Axiom: `a.uintValue == b.uintValue` iff `a == b` var uintValue: UInt { get } /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } /// Construct an instance that uniquely identifies the class instance `x`. init(_ x: AnyObject) /// Construct an instance that uniquely identifies the metatype `x`. init(_ x: Any.Type) } enum Optional<T> : Reflectable, NilLiteralConvertible { case None case Some(T) /// Construct a `nil` instance. init() /// Construct a non-\ `nil` instance that stores `some`. init(_ some: T) /// If `self == nil`, returns `nil`. Otherwise, returns `f(self!)`. func map<U>(f: @noescape (T) -> U) -> U? /// Returns `f(self)!` iff `self` and `f(self)` are not nil. func flatMap<U>(f: @noescape (T) -> U?) -> U? /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType /// Create an instance initialized with `nil`. init(nilLiteral: ()) } extension Optional : DebugPrintable { /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } /// A target of text streaming operations. protocol OutputStreamType { /// Append the given `string` to this stream. mutating func write(string: String) } /// A *generator* that adapts a *collection* `C` and any *sequence* of /// its `Index` type to present the collection's elements in a /// permuted order. struct PermutationGenerator<C : CollectionType, Indices : SequenceType> : GeneratorType, SequenceType { /// The type of element returned by `next()`. typealias Element = C.Generator.Element /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// Requires: no preceding call to `self.next()` has returned `nil`. mutating func next() -> Element? /// A type whose instances can produce the elements of this /// sequence, in order. typealias Generator = PermutationGenerator<C, Indices> /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> PermutationGenerator<C, Indices> /// Construct a *generator* over a permutation of `elements` given /// by `indices`. /// /// Requires: `elements[i]` is valid for every `i` in `indices`. init(elements: C, indices: Indices) } /// A type with a customized textual representation. /// /// This textual representation is used when values are written to an /// *output stream*, for example, by `print` and `println`. /// /// In order to generate a textual representation for an instance of any /// type (which might or might not conform to `Printable`), use `toString`. protocol Printable { /// A textual representation of `self`. var description: String { get } } enum Process { /// The list of command-line arguments with which the current /// process was invoked. static let arguments: [String] /// Access to the raw argc value from C. static var argc: CInt { get } /// Access to the raw argv value from C. Accessing the argument vector /// through this pointer is unsafe. static var unsafeArgv: UnsafeMutablePointer<UnsafeMutablePointer<Int8>> { get } } /// The sum of types that can be used as a quick look representation. enum QuickLookObject { case Text(String) case Int(Int64) case UInt(UInt64) case Float(Float32) case Double(Float64) case Image(Any) case Sound(Any) case Color(Any) case BezierPath(Any) case AttributedString(Any) case Rectangle(Float64, Float64, Float64, Float64) case Point(Float64, Float64) case Size(Float64, Float64) case Logical(Bool) case Range(UInt64, UInt64) case View(Any) case Sprite(Any) case URL(String) } /// An *index* that can be offset by an arbitrary number of positions, /// and can measure the distance to any reachable value, in O(1). protocol RandomAccessIndexType : BidirectionalIndexType, _RandomAccessIndexType { } /// The lazy `CollectionType` returned by `reverse(c)` where `c` is a /// `CollectionType` with an `Index` conforming to `RandomAccessIndexType` struct RandomAccessReverseView<T : CollectionType where T.Index : RandomAccessIndexType> : CollectionType { /// 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. typealias Index = ReverseRandomAccessIndex<T.Index> /// A type whose instances can produce the elements of this /// sequence, in order. typealias Generator = IndexingGenerator<RandomAccessReverseView<T>> /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> IndexingGenerator<RandomAccessReverseView<T>> /// The position of the first element in a non-empty collection. /// /// Identical to `endIndex` in an empty collection. var startIndex: Index { get } /// 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()`. var endIndex: Index { get } subscript (position: Index) -> T.Generator.Element { get } } /// A collection of consecutive discrete index values. /// /// :param: `T` is both the element type and the index type of the /// collection. /// /// Like other collections, a range containing one element has an /// `endIndex` that is the successor of its `startIndex`; and an empty /// range has `startIndex == endIndex`. /// /// Axiom: for any `Range` `r`, `r[i] == i`. /// /// Therefore, if `T` has a maximal value, it can serve as an /// `endIndex`, but can never be contained in a `Range<T>`. /// /// It also follows from the axiom above that `(-99..<100)[0] == 0`. /// To prevent confusion (because some expect the result to be `-99`), /// in a context where `T` is known to be an integer type, /// subscripting with `T` is a compile-time error:: /// /// // error: could not find an overload for 'subscript'... /// println( Range<Int>(start:-99, end:100)[0] ) /// /// However, subscripting that range still works in a generic context:: /// /// func brackets<T:ForwardIndexType>(x: Range<T>, i: T) -> T { /// return x[i] // Just forward to subscript /// } /// println(brackets(Range<Int>(start:-99, end:100), 0)) // prints 0 struct Range<T : ForwardIndexType> : Equatable, CollectionType, Printable, DebugPrintable { /// Construct a copy of `x` init(_ x: Range<T>) /// Construct a range with `startIndex == start` and `endIndex == /// end`. init(start: T, end: T) /// `true` iff the range is empty, i.e. `startIndex == endIndex` var isEmpty: Bool { get } /// 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. typealias Index = T typealias ArraySlice = Range<T> subscript (position: T) -> T { get } //subscript (_: T._DisabledRangeIndex) -> T { get } /// A type whose instances can produce the elements of this /// sequence, in order. typealias Generator = RangeGenerator<T> /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> RangeGenerator<T> /// The range's lower bound /// /// Identical to `endIndex` in an empty range. var startIndex: T /// The range's upper bound /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. var endIndex: T /// A textual representation of `self`. var description: String { get } /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } extension Range { /// Return an array containing the results of calling /// `transform(x)` on each element `x` of `self`. func map<U>(transform: (T) -> U) -> [U] } extension Range : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } /// A generator over the elements of `Range<T>` struct RangeGenerator<T : ForwardIndexType> : GeneratorType, SequenceType { /// The type of element returned by `next()`. typealias Element = T /// Construct an instance that traverses the elements of `bounds` init(_ bounds: Range<T>) /// Advance to the next element and return it, or `nil` if no next /// element exists. mutating func next() -> T? /// A type whose instances can produce the elements of this /// sequence, in order. typealias Generator = RangeGenerator<T> /// `RangeGenerator` is also a `SequenceType`, so it /// `generate`\ 's a copy of itself func generate() -> RangeGenerator<T> /// The lower bound of the remaining range. var startIndex: T /// The upper bound of the remaining range; not included in the /// generated sequence. var endIndex: T } /// A *collection* that supports replacement of an arbitrary subRange /// of elements with the elements of another collection. protocol RangeReplaceableCollectionType : ExtensibleCollectionType { /// Replace the given `subRange` of elements with `newElements`. /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count(subRange)`\ ) if /// `subRange.endIndex == self.endIndex` and `isEmpty(newElements)`, /// O(\ `count(self)` + `count(newElements)`\ ) otherwise. mutating func replaceRange<C : CollectionType>(subRange: Range<Self.Index>, with newElements: C) /// Insert `newElement` at index `i`. /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count(self)`\ ). /// /// Can be implemented as:: /// /// Swift.insert(&self, newElement, atIndex: i) mutating func insert(newElement: Self.Generator.Element, atIndex i: Self.Index) /// Insert `newElements` at index `i` /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count(self) + count(newElements)`\ ). /// /// Can be implemented as:: /// /// Swift.splice(&self, newElements, atIndex: i) mutating func splice<S : CollectionType>(newElements: S, atIndex i: Self.Index) /// Remove the element at index `i` /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count(self)`\ ). /// /// Can be implemented as:: /// /// Swift.removeAtIndex(&self, i) mutating func removeAtIndex(i: Self.Index) -> Self.Generator.Element /// Remove the indicated `subRange` of elements /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count(self)`\ ). /// /// Can be implemented as:: /// /// Swift.removeRange(&self, subRange) mutating func removeRange(subRange: Range<Self.Index>) /// Remove all elements /// /// Invalidates all indices with respect to `self`. /// /// :param: `keepCapacity`, if `true`, is a non-binding request to /// avoid releasing storage, which can be a useful optimization /// when `self` is going to be grown again. /// /// Complexity: O(\ `count(self)`\ ). /// /// Can be implemented as:: /// /// Swift.removeAll(&self, keepCapacity: keepCapacity) mutating func removeAll(#keepCapacity: Bool) } /// A byte-sized thing that isn't designed to interoperate with /// any other types; it makes a decent parameter to UnsafeMutablePointer when /// you just want to do bytewise pointer arithmetic. struct RawByte { } /// Protocol for `NS_OPTIONS` imported from Objective-C protocol RawOptionSetType : _RawOptionSetType, BitwiseOperationsType, NilLiteralConvertible { } /// A type that can be converted to an associated "raw" type, then /// converted back to produce an instance equivalent to the original. protocol RawRepresentable { /// The "raw" type that can be used to represent all values of `Self`. /// /// Every distinct value of `self` has a corresponding unique /// value of `RawValue`, but `RawValue` may have representations /// that do not correspond to an value of `Self`. typealias RawValue /// Convert from a value of `RawValue`, yielding `nil` iff /// `rawValue` does not correspond to a value of `Self`. init?(rawValue: RawValue) /// The corresponding value of the "raw" type. /// /// `Self(rawValue: self.rawValue)!` is equivalent to `self`. var rawValue: RawValue { get } } /// Customizes the result of `reflect(x)`, where `x` is a conforming /// type. protocol Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } /// A collection whose elements are all identical `T`\ s. struct Repeat<T> : CollectionType { /// 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. typealias Index = Int /// Construct an instance that contains `count` elements having the /// value `repeatedValue`. init(count: Int, repeatedValue: T) /// Always zero, which is the index of the first element in a /// non-empty instance. var startIndex: Index { get } /// Always equal to `count`, which is one greater than the index of /// the last element in a non-empty instance. var endIndex: Index { get } /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> IndexingGenerator<Repeat<T>> subscript (position: Int) -> T { get } /// The number of elements in this collection. var count: Int /// The value of every element in this collection. let repeatedValue: T } /// A wrapper for a `BidirectionalIndexType` that reverses its /// direction of traversal struct ReverseBidirectionalIndex<I : BidirectionalIndexType> : BidirectionalIndexType { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> ReverseBidirectionalIndex<I> /// Returns the previous consecutive value before `self`. /// /// Requires: the previous value is representable. func predecessor() -> ReverseBidirectionalIndex<I> } /// A wrapper for a `RandomAccessIndexType` that reverses its /// direction of traversal struct ReverseRandomAccessIndex<I : RandomAccessIndexType> : RandomAccessIndexType { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> ReverseRandomAccessIndex<I> /// Returns the previous consecutive value before `self`. /// /// Requires: the previous value is representable. func predecessor() -> ReverseRandomAccessIndex<I> /// Return the minimum number of applications of `successor` or /// `predecessor` required to reach `other` from `self`. /// /// Complexity: O(1). func distanceTo(other: ReverseRandomAccessIndex<I>) -> I.Distance /// Return `self` offset by `n` steps. /// /// :returns: If `n > 0`, the result of applying `successor` to /// `self` `n` times. If `n < 0`, the result of applying /// `predecessor` to `self` `-n` times. Otherwise, `self`. /// /// Complexity: O(1) func advancedBy(amount: I.Distance) -> ReverseRandomAccessIndex<I> } /// A type-erased sequence. /// /// Forwards operations to an arbitrary underlying sequence with the /// same `Element` type, hiding the specifics of the underlying /// sequence type. /// /// See also: `GeneratorOf<T>`. struct SequenceOf<T> : SequenceType { /// Construct an instance whose `generate()` method forwards to /// `makeUnderlyingGenerator` init<G : GeneratorType>(_ makeUnderlyingGenerator: () -> G) /// Construct an instance whose `generate()` method forwards to /// that of `base`. init<S : SequenceType>(_ base: S) /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> GeneratorOf<T> } /// A type that can be iterated with a `for`\ ...\ `in` loop. /// /// `SequenceType` makes no requirement on conforming types regarding /// whether they will be destructively "consumed" by iteration. To /// ensure non-destructive iteration, constrain your *sequence* to /// `CollectionType`. protocol SequenceType : _Sequence_Type { /// A type that provides the *sequence*\ 's iteration interface and /// encapsulates its iteration state. typealias Generator : GeneratorType /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> Generator } /// A collection of unique `T` instances with no defined ordering. struct Set<T : Hashable> : Hashable, CollectionType, ArrayLiteralConvertible { typealias Element = T typealias Index = SetIndex<T> typealias GeneratorType = SetGenerator<T> /// Create an empty set with at least the given number of /// elements worth of storage. The actual capacity will be the /// smallest power of 2 that's >= `minimumCapacity`. init(minimumCapacity: Int) /// The position of the first element in a non-empty set. /// /// This is identical to `endIndex` in an empty set. /// /// Complexity: amortized O(1) if `self` does not wrap a bridged /// `NSSet`, O(N) otherwise. var startIndex: SetIndex<T> { get } /// 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()`. /// /// Complexity: amortized O(1) if `self` does not wrap a bridged /// `NSSet`, O(N) otherwise. var endIndex: SetIndex<T> { get } /// Returns `true` if the set contains a member. func contains(member: T) -> Bool /// Returns the `Index` of a given member, or `nil` if the member is not /// present in the set. func indexOf(member: T) -> SetIndex<T>? /// Insert a member into the set. mutating func insert(member: T) /// Remove the member from the set and return it if it was present. mutating func remove(member: T) -> T? /// Remove the member referenced by the given index. mutating func removeAtIndex(index: SetIndex<T>) /// Erase all the elements. If `keepCapacity` is `true`, `capacity` /// will not decrease. mutating func removeAll(keepCapacity: Bool) /// Remove a member from the set and return it. Requires: `count > 0`. mutating func removeFirst() -> T /// The number of members in the set. /// /// Complexity: O(1) var count: Int { get } subscript (position: SetIndex<T>) -> T { get } /// Return a *generator* over the members. /// /// Complexity: O(1) func generate() -> SetGenerator<T> init(arrayLiteral elements: T...) /// Create an empty `Set`. init() /// Create a `Set` from a finite sequence of items. init<S : SequenceType>(_ sequence: S) /// The first element obtained when iterating, or `nil` if `self` is /// empty. Equivalent to `self.generate().next()` var first: T? { get } /// Returns true if the set is a subset of a finite sequence as a `Set`. func isSubsetOf<S : SequenceType>(sequence: S) -> Bool /// Returns true if the set is a subset of a finite sequence as a `Set` /// but not equal. func isStrictSubsetOf<S : SequenceType>(sequence: S) -> Bool /// Returns true if the set is a superset of a finite sequence as a `Set`. func isSupersetOf<S : SequenceType>(sequence: S) -> Bool /// Returns true if the set is a superset of a finite sequence as a `Set` /// but not equal. func isStrictSupersetOf<S : SequenceType>(sequence: S) -> Bool /// Returns true if no members in the set are in a finite sequence as a `Set`. func isDisjointWith<S : SequenceType>(sequence: S) -> Bool /// Return a new `Set` with items in both this set and a finite sequence. func union<S : SequenceType>(sequence: S) -> Set<T> /// Insert elements of a finite sequence into this `Set`. mutating func unionInPlace<S : SequenceType>(sequence: S) /// Return a new set with elements in this set that do not occur /// in a finite sequence. func subtract<S : SequenceType>(sequence: S) -> Set<T> /// Remove all members in the set that occur in a finite sequence. mutating func subtractInPlace<S : SequenceType>(sequence: S) /// Return a new set with elements common to this set and a finite sequence. func intersect<S : SequenceType>(sequence: S) -> Set<T> /// Remove any members of this set that aren't also in a finite sequence. mutating func intersectInPlace<S : SequenceType>(sequence: S) /// Return a new set with elements that are either in the set or a finite /// sequence but do not occur in both. func exclusiveOr<S : SequenceType>(sequence: S) -> Set<T> /// For each element of a finite sequence, remove it from the set if it is a /// common element, otherwise add it to the set. Repeated elements of the /// sequence will be ignored. mutating func exclusiveOrInPlace<S : SequenceType>(sequence: S) /// `true` if the set is empty. var isEmpty: Bool { get } var hashValue: Int { get } } extension Set : Printable, DebugPrintable { /// A textual representation of `self`. var description: String { get } /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } extension Set : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } /// A generator over the members of a `Set<T>` struct SetGenerator<T : Hashable> : GeneratorType { /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// Requires: no preceding call to `self.next()` has returned `nil`. mutating func next() -> T? } /// Used to access the members in an instance of `Set<T>`. struct SetIndex<T : Hashable> : ForwardIndexType, Comparable { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> SetIndex<T> } /// A set of common requirements for Swift's signed integer types. protocol SignedIntegerType : _SignedIntegerType, IntegerType { } /// Instances of conforming types can be subtracted, arithmetically /// negated, and initialized from `0`. /// /// Axioms: /// /// - `x - 0 == x` /// - `-x == 0 - x` /// - `-(-x) == x` protocol SignedNumberType : _SignedNumberType { /// Return the result of negating `x`. prefix func -(x: Self) -> Self } /// A type-erased sink. /// /// Forwards operations to an arbitrary underlying sink with the same /// `Element` type, hiding the specifics of the underlying sink type. struct SinkOf<T> : SinkType { /// Construct an instance whose `put(x)` calls `putElement(x)` init(_ putElement: (T) -> ()) /// Construct an instance whose `put(x)` calls `base.put(x)` init<S : SinkType>(_ base: S) /// Write `x` to this sink. func put(x: T) } /// Instances of conforming types are effectively functions with the /// signature `(Element) -> Void`. /// /// Useful mainly when the optimizer's ability to specialize generics /// outstrips its ability to specialize ordinary closures. For /// example, you may find that instead of:: /// /// func f(g: (X)->Void) { ... g(a) ...} /// /// the following generates better code:: /// /// func f<T: Sink where T.Element == X>(g: T) { ... g.put(a) ...} protocol SinkType { /// The type of element to be written to this sink. typealias Element /// Write `x` to this sink. mutating func put(x: Element) } /// A *collection* from which a sub-range of elements (a "slice") /// can be efficiently extracted. protocol Sliceable : _Sliceable { /// The *collection* type that represents a sub-range of elements. /// /// Though it can't currently be enforced by the type system, the /// `SubSlice` type in a concrete implementation of `Sliceable` /// should also be `Sliceable`. typealias SubSlice : _Sliceable subscript (bounds: Range<Self.Index>) -> SubSlice { get } } /// An simple string designed to represent text that is "knowable at /// compile-time". /// /// Logically speaking, each instance looks something like this:: /// /// enum StaticString { /// case ASCII(start: UnsafePointer<UInt8>, length: Int) /// case UTF8(start: UnsafePointer<UInt8>, length: Int) /// case Scalar(UnicodeScalar) /// } struct StaticString : UnicodeScalarLiteralConvertible, ExtendedGraphemeClusterLiteralConvertible, StringLiteralConvertible, Printable, DebugPrintable { /// A pointer to the beginning of UTF-8 code units /// /// Requires: `self` stores a pointer to either ASCII or UTF-8 code /// units. var utf8Start: UnsafePointer<UInt8> { get } /// The stored Unicode scalar value /// /// Requires: `self` stores a single Unicode scalar value. var unicodeScalar: UnicodeScalar { get } /// If `self` stores a pointer to ASCII or UTF-8 code units, the /// length in bytes of that data. /// /// If `self` stores a single Unicode scalar value, the value of /// `byteSize` is unspecified. var byteSize: Word { get } /// `true` iff `self` stores a pointer to ASCII or UTF-8 code units var hasPointerRepresentation: Bool { get } /// `true` if `self` stores a pointer to ASCII code units. /// /// If `self` stores a single Unicode scalar value, the value of /// `isASCII` is unspecified. var isASCII: Bool { get } /// Invoke `body` with a buffer containing the UTF-8 code units of /// `self`. /// /// This method works regardless of what `self` stores. func withUTF8Buffer<R>(body: @noescape (UnsafeBufferPointer<UInt8>) -> R) -> R /// Return a `String` representing the same sequence of Unicode /// scalar values as `self` does. var stringValue: String { get } /// Create an empty instance. init() init(_builtinUnicodeScalarLiteral value: Builtin.Int32) /// Create an instance initialized to `value`. init(unicodeScalarLiteral value: StaticString) init(_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, byteSize: Builtin.Word, isASCII: Builtin.Int1) /// Create an instance initialized to `value`. init(extendedGraphemeClusterLiteral value: StaticString) init(_builtinStringLiteral start: Builtin.RawPointer, byteSize: Builtin.Word, isASCII: Builtin.Int1) /// Create an instance initialized to `value`. init(stringLiteral value: StaticString) /// A textual representation of `self`. var description: String { get } /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } /// A source of text streaming operations. `Streamable` instances can /// be written to any *output stream*. /// /// For example: `String`, `Character`, `UnicodeScalar`. protocol Streamable { /// Write a textual representation of `self` into `target` func writeTo<Target : OutputStreamType>(inout target: Target) } /// A `SequenceType` of values formed by striding over a closed interval struct StrideThrough<T : Strideable> : SequenceType { /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> StrideThroughGenerator<T> } extension StrideThrough : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } /// A GeneratorType for StrideThrough<T> struct StrideThroughGenerator<T : Strideable> : GeneratorType { /// Advance to the next element and return it, or `nil` if no next /// element exists. mutating func next() -> T? } /// A `SequenceType` of values formed by striding over a half-open interval struct StrideTo<T : Strideable> : SequenceType { /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> StrideToGenerator<T> } extension StrideTo : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } /// A GeneratorType for StrideTo<T> struct StrideToGenerator<T : Strideable> : GeneratorType { /// Advance to the next element and return it, or `nil` if no next /// element exists. mutating func next() -> T? } /// Conforming types are notionally continuous, one-dimensional /// values that can be offset and measured. /// /// See also: `stride(from: to: by:)` and `stride(from: through: by:)` protocol Strideable : Comparable, _Strideable { } /// An arbitrary Unicode string value. /// /// Unicode-Correct /// =============== /// /// Swift strings are designed to be Unicode-correct. In particular, /// the APIs make it easy to write code that works correctly, and does /// not surprise end-users, regardless of where you venture in the /// Unicode character space. For example, /// /// * The `==` operator checks for `Unicode canonical equivalence /// <http://www.unicode.org/glossary/#deterministic_comparison>`_, /// so two different representations of the same string will always /// compare equal. /// /// * String elements are `Characters` (`extended grapheme clusters /// <http://www.unicode.org/glossary/#extended_grapheme_cluster>`_), /// a unit of text that is meaningful to most humans. /// /// Locale-Insensitive /// ================== /// /// The fundamental operations on Swift strings are not sensitive to /// locale settings. That's because, for example, the validity of a /// `Dictionary<String, T>` in a running program depends on a given /// string comparison having a single, stable result. Therefore, /// Swift always uses the default, un-\ `tailored /// <http://www.unicode.org/glossary/#tailorable>`_ Unicode algorithms /// for basic string operations. /// /// Importing `Foundation` endows swift strings with the full power of /// the `NSString` API, which allows you to choose more complex /// locale-sensitive operations explicitly. /// /// Value Semantics /// =============== /// /// Each string variable, `let` binding, or stored property has an /// independent value, so mutations to the string are not observable /// through its copies:: /// /// var a = "foo" /// var b = a /// b[b.endIndex.predecessor()] = "x" /// println("a=\(a), b=\(b)") // a=foo, b=fox /// /// Strings use Copy-on-Write so that their data is only copied /// lazily, upon mutation, when more than one string instance is using /// the same buffer. Therefore, the first in any sequence of mutating /// operations may cost `O(N)` time and space, where `N` is the length /// of the string's (unspecified) underlying representation,. /// /// Growth and Capacity /// =================== /// /// When a string's contiguous storage fills up, new storage must be /// allocated and characters must be moved to the new storage. /// `String` uses an exponential growth strategy that makes `append` a /// constant time operation *when amortized over many invocations*. /// /// Objective-C Bridge /// ================== /// /// `String` is bridged to Objective-C as `NSString`, and a `String` /// that originated in Objective-C may store its characters in an /// `NSString`. Since any arbitrary subclass of `NSSString` can /// become a `String`, there are no guarantees about representation or /// efficiency in this case. Since `NSString` is immutable, it is /// just as though the storage was shared by some copy: the first in /// any sequence of mutating operations causes elements to be copied /// into unique, contiguous storage which may cost `O(N)` time and /// space, where `N` is the length of the string representation (or /// more, if the underlying `NSString` is has unusual performance /// characteristics). struct String { init() } extension String : CollectionType { /// A character position in a `String` struct Index : BidirectionalIndexType, Comparable, Reflectable { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> String.Index /// Returns the previous consecutive value before `self`. /// /// Requires: the previous value is representable. func predecessor() -> String.Index /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } /// The position of the first `Character` if the `String` is /// non-empty; identical to `endIndex` otherwise. var startIndex: String.Index { get } /// The `String`\ '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()`. var endIndex: String.Index { get } subscript (i: String.Index) -> Character { get } /// Return a *generator* over the `Characters` in this `String`. /// /// Complexity: O(1) func generate() -> IndexingGenerator<String> } extension String { /// A collection of UTF-16 code units that encodes a `String` value. struct UTF16View : Sliceable, Reflectable, Printable, DebugPrintable { struct Index { } /// The position of the first code unit if the `String` is /// non-empty; identical to `endIndex` otherwise. var startIndex: String.UTF16View.Index { get } /// The "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()`. var endIndex: String.UTF16View.Index { get } /// A type whose instances can produce the elements of this /// sequence, in order. //COMMENTED: typealias Generator /// Return a *generator* over the code points that comprise this /// *sequence*. /// /// Complexity: O(1) //COMMENTED: func generate() -> Generator subscript (i: String.UTF16View.Index) -> UInt16 { get } subscript (subRange: Range<String.UTF16View.Index>) -> String.UTF16View { get } /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType var description: String { get } var debugDescription: String { get } } /// A UTF-16 encoding of `self`. var utf16: String.UTF16View { get } /// Construct the `String` corresponding to the given sequence of /// UTF-16 code units. If `utf16` contains unpaired surrogates, the /// result is `nil`. init?(_ utf16: String.UTF16View) /// The index type for subscripting a `String`\ 's `utf16` view. typealias UTF16Index = String.UTF16View.Index } extension String { typealias CodeUnit = UInt32 /// A collection of UTF-8 code units that encodes a `String` value. struct UTF8View : CollectionType, Reflectable, Printable, DebugPrintable { /// A position in a `String.UTF8View` struct Index : ForwardIndexType { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> String.UTF8View.Index } /// The position of the first code unit if the `String` is /// non-empty; identical to `endIndex` otherwise. var startIndex: String.UTF8View.Index { get } /// The "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()`. var endIndex: String.UTF8View.Index { get } subscript (position: String.UTF8View.Index) -> CodeUnit { get } subscript (subRange: Range<String.UTF8View.Index>) -> String.UTF8View { get } /// Return a *generator* over the code points that comprise this /// *sequence*. /// /// Complexity: O(1) func generate() -> IndexingGenerator<String.UTF8View> /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType var description: String { get } var debugDescription: String { get } } /// A UTF-8 encoding of `self`. var utf8: String.UTF8View { get } /// A contiguously-stored nul-terminated UTF-8 representation of /// `self`. /// /// To access the underlying memory, invoke /// `withUnsafeBufferPointer` on the `ContiguousArray`. var nulTerminatedUTF8: ContiguousArray<CodeUnit> { get } /// Construct the `String` corresponding to the given sequence of /// UTF-8 code units. If `utf8` contains unpaired surrogates, the /// result is `nil`. init?(_ utf8: String.UTF8View) /// The index type for subscripting a `String`\ 's `.utf8` view. typealias UTF8Index = String.UTF8View.Index } extension String { /// A collection of `Unicode scalar values /// <http://www.unicode.org/glossary/#unicode_scalar_value>`_ that /// encode a `String` . struct UnicodeScalarView : Sliceable, SequenceType, Reflectable, Printable, DebugPrintable { /// A position in a `String.UnicodeScalarView` struct Index : BidirectionalIndexType, Comparable { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> String.UnicodeScalarView.Index /// Returns the previous consecutive value before `self`. /// /// Requires: the previous value is representable. func predecessor() -> String.UnicodeScalarView.Index } /// The position of the first `UnicodeScalar` if the `String` is /// non-empty; identical to `endIndex` otherwise. var startIndex: String.UnicodeScalarView.Index { get } /// The "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()`. var endIndex: String.UnicodeScalarView.Index { get } subscript (position: String.UnicodeScalarView.Index) -> UnicodeScalar { get } subscript (r: Range<String.UnicodeScalarView.Index>) -> String.UnicodeScalarView { get } /// A type whose instances can produce the elements of this /// sequence, in order. struct Generator : GeneratorType { /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// Requires: no preceding call to `self.next()` has returned /// `nil`. mutating func next() -> UnicodeScalar? } /// Return a *generator* over the `UnicodeScalar`\ s that comprise /// this *sequence*. /// /// Complexity: O(1) func generate() -> String.UnicodeScalarView.Generator /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType var description: String { get } var debugDescription: String { get } } /// Construct the `String` corresponding to the given sequence of /// Unicode scalars. init(_ unicodeScalars: String.UnicodeScalarView) /// The index type for subscripting a `String`\ 's `.unicodeScalars` /// view. typealias UnicodeScalarIndex = String.UnicodeScalarView.Index } extension String { /// Creates a new `String` by copying the nul-terminated UTF-8 data /// referenced by a `CString`. /// /// Returns `nil` if the `CString` is `NULL` or if it contains ill-formed /// UTF-8 code unit sequences. static func fromCString(cs: UnsafePointer<CChar>) -> String? /// Creates a new `String` by copying the nul-terminated UTF-8 data /// referenced by a `CString`. /// /// Returns `nil` if the `CString` is `NULL`. If `CString` contains /// ill-formed UTF-8 code unit sequences, replaces them with replacement /// characters (U+FFFD). static func fromCStringRepairingIllFormedUTF8(cs: UnsafePointer<CChar>) -> (String?, hadError: Bool) } extension String { /// Construct an instance containing just the given `Character`. init(_ c: Character) } extension String { /// Invoke `f` on the contents of this string, represented as /// a nul-terminated array of char, ensuring that the array's /// lifetime extends through the execution of `f`. func withCString<Result>(f: @noescape UnsafePointer<Int8> -> Result) -> Result } extension String : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension String : OutputStreamType { /// Append `other` to this stream. mutating func write(other: String) } extension String : Streamable { /// Write a textual representation of `self` into `target` func writeTo<Target : OutputStreamType>(inout target: Target) } extension String { init(_builtinUnicodeScalarLiteral value: Builtin.Int32) } extension String : UnicodeScalarLiteralConvertible { /// Create an instance initialized to `value`. init(unicodeScalarLiteral value: String) } extension String { init(_builtinExtendedGraphemeClusterLiteral start: Builtin.RawPointer, byteSize: Builtin.Word, isASCII: Builtin.Int1) } extension String : ExtendedGraphemeClusterLiteralConvertible { /// Create an instance initialized to `value`. init(extendedGraphemeClusterLiteral value: String) } extension String { init(_builtinUTF16StringLiteral start: Builtin.RawPointer, numberOfCodeUnits: Builtin.Word) } extension String { init(_builtinStringLiteral start: Builtin.RawPointer, byteSize: Builtin.Word, isASCII: Builtin.Int1) } extension String : StringLiteralConvertible { /// Create an instance initialized to `value`. init(stringLiteral value: String) } extension String : DebugPrintable { /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } extension String : Equatable { } extension String : Comparable { } extension String { /// Append the elements of `other` to `self`. mutating func extend(other: String) /// Append `x` to `self`. /// /// Complexity: amortized O(1). mutating func append(x: UnicodeScalar) } extension String : Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } extension String : StringInterpolationConvertible { /// Create an instance by concatenating the elements of `strings` init(stringInterpolation strings: String...) /// Create an instance containing `expr`\ 's `print` representation init<T>(stringInterpolationSegment expr: T) } extension String : Sliceable { subscript (subRange: Range<String.Index>) -> String { get } } extension String : ExtensibleCollectionType { /// Reserve enough space to store `n` ASCII characters. /// /// Complexity: O(`n`) mutating func reserveCapacity(n: Int) /// Append `c` to `self`. /// /// Complexity: amortized O(1). mutating func append(c: Character) /// Append the elements of `newElements` to `self`. mutating func extend<S : SequenceType where Character == Character>(newElements: S) /// Create an instance containing `characters`. init<S : SequenceType where Character == Character>(_ characters: S) } extension String { /// Interpose `self` between every pair of consecutive `elements`, /// then concatenate the result. For example:: /// /// "-|-".join(["foo", "bar", "baz"]) // "foo-|-bar-|-baz" func join<S : SequenceType where String == String>(elements: S) -> String } extension String : RangeReplaceableCollectionType { /// Replace the given `subRange` of elements with `newElements`. /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count(subRange)`\ ) if `subRange.endIndex /// == self.endIndex` and `isEmpty(newElements)`\ , O(N) otherwise. mutating func replaceRange<C : CollectionType where Character == Character>(subRange: Range<String.Index>, with newElements: C) /// Insert `newElement` at index `i`. /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count(self)`\ ). mutating func insert(newElement: Character, atIndex i: String.Index) /// Insert `newElements` at index `i` /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count(self) + count(newElements)`\ ). mutating func splice<S : CollectionType where Character == Character>(newElements: S, atIndex i: String.Index) /// Remove and return the element at index `i` /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count(self)`\ ). mutating func removeAtIndex(i: String.Index) -> Character /// Remove the indicated `subRange` of characters /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count(self)`\ ). mutating func removeRange(subRange: Range<String.Index>) /// Remove all characters. /// /// Invalidates all indices with respect to `self`. /// /// :param: `keepCapacity`, if `true`, prevents the release of /// allocated storage, which can be a useful optimization /// when `self` is going to be grown again. mutating func removeAll(keepCapacity: Bool) } extension String { var lowercaseString: String { get } var uppercaseString: String { get } } extension String : StringInterpolationConvertible { init(stringInterpolationSegment expr: String) init(stringInterpolationSegment expr: Character) init(stringInterpolationSegment expr: UnicodeScalar) init(stringInterpolationSegment expr: Bool) init(stringInterpolationSegment expr: Float32) init(stringInterpolationSegment expr: Float64) init(stringInterpolationSegment expr: UInt8) init(stringInterpolationSegment expr: Int8) init(stringInterpolationSegment expr: UInt16) init(stringInterpolationSegment expr: Int16) init(stringInterpolationSegment expr: UInt32) init(stringInterpolationSegment expr: Int32) init(stringInterpolationSegment expr: UInt64) init(stringInterpolationSegment expr: Int64) init(stringInterpolationSegment expr: UInt) init(stringInterpolationSegment expr: Int) } extension String { /// Construct an instance that is the concatenation of `count` copies /// of `repeatedValue` init(count: Int, repeatedValue c: Character) /// Construct an instance that is the concatenation of `count` copies /// of `Character(repeatedValue)` init(count: Int, repeatedValue c: UnicodeScalar) /// `true` iff `self` contains no characters. var isEmpty: Bool { get } } extension String { /// Return `true` iff `self` begins with `prefix` func hasPrefix(prefix: String) -> Bool /// Return `true` iff `self` ends with `suffix` func hasSuffix(suffix: String) -> Bool } extension String { /// Create an instance representing `v` in base 10. init<T : _SignedIntegerType>(_ v: T) /// Create an instance representing `v` in base 10. init<T : _UnsignedIntegerType>(_ v: T) /// Create an instance representing `v` in the given `radix` (base). /// /// Numerals greater than 9 are represented as roman letters, /// starting with `a` if `uppercase` is `false` or `A` otherwise. init<T : _SignedIntegerType>(_ v: T, radix: Int, uppercase: Bool) /// Create an instance representing `v` in the given `radix` (base). /// /// Numerals greater than 9 are represented as roman letters, /// starting with `a` if `uppercase` is `false` or `A` otherwise. init<T : _UnsignedIntegerType>(_ v: T, radix: Int, uppercase: Bool) } extension String { /// If the string represents an integer that fits into an Int, returns /// the corresponding integer. This accepts strings that match the regular /// expression "[-+]?[0-9]+" only. func toInt() -> Int? } extension String { /// The value of `self` as a collection of `Unicode scalar values /// <http://www.unicode.org/glossary/#unicode_scalar_value>`_. var unicodeScalars: String.UnicodeScalarView } extension String.Index { /// Construct the position in `characters` that corresponds exactly to /// `unicodeScalarIndex`. If no such position exists, the result is `nil`. /// /// Requires: `unicodeScalarIndex` is an element of /// `indices(characters.unicodeScalars)`. init?(_ unicodeScalarIndex: UnicodeScalarIndex, within characters: String) /// Construct the position in `characters` that corresponds exactly to /// `utf16Index`. If no such position exists, the result is `nil`. /// /// Requires: `utf16Index` is an element of /// `indices(characters.utf16)`. init?(_ utf16Index: UTF16Index, within characters: String) /// Construct the position in `characters` that corresponds exactly to /// `utf8Index`. If no such position exists, the result is `nil`. /// /// Requires: `utf8Index` is an element of /// `indices(characters.utf8)`. init?(_ utf8Index: UTF8Index, within characters: String) /// Return the position in `utf8` that corresponds exactly /// to `self`. /// /// Requires: `self` is an element of `indices(String(utf8))`. func samePositionIn(utf8: String.UTF8View) -> String.UTF8View.Index /// Return the position in `utf16` that corresponds exactly /// to `self`. /// /// Requires: `self` is an element of `indices(String(utf16))`. func samePositionIn(utf16: String.UTF16View) -> String.UTF16View.Index /// Return the position in `unicodeScalars` that corresponds exactly /// to `self`. /// /// Requires: `self` is an element of `indices(String(unicodeScalars))`. func samePositionIn(unicodeScalars: String.UnicodeScalarView) -> String.UnicodeScalarView.Index } extension String.UnicodeScalarView : ExtensibleCollectionType { /// Construct an empty instance. init() /// Reserve enough space to store `n` ASCII characters. /// /// Complexity: O(`n`) mutating func reserveCapacity(n: Int) /// Append `x` to `self`. /// /// Complexity: amortized O(1). mutating func append(x: UnicodeScalar) /// Append the elements of `newElements` to `self`. /// /// Complexity: O(*length of result*) mutating func extend<S : SequenceType where UnicodeScalar == UnicodeScalar>(newElements: S) } extension String.UnicodeScalarView : RangeReplaceableCollectionType { /// Replace the given `subRange` of elements with `newElements`. /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count(subRange)`\ ) if `subRange.endIndex /// == self.endIndex` and `isEmpty(newElements)`\ , O(N) otherwise. mutating func replaceRange<C : CollectionType where UnicodeScalar == UnicodeScalar>(subRange: Range<String.UnicodeScalarView.Index>, with newElements: C) /// Insert `newElement` at index `i`. /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count(self)`\ ). mutating func insert(newElement: UnicodeScalar, atIndex i: String.UnicodeScalarView.Index) /// Insert `newElements` at index `i` /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count(self) + count(newElements)`\ ). mutating func splice<S : CollectionType where UnicodeScalar == UnicodeScalar>(newElements: S, atIndex i: String.UnicodeScalarView.Index) /// Remove the and return element at index `i` /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count(self)`\ ). mutating func removeAtIndex(i: String.UnicodeScalarView.Index) -> UnicodeScalar /// Remove the indicated `subRange` of elements /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count(self)`\ ). mutating func removeRange(subRange: Range<String.UnicodeScalarView.Index>) /// Remove all elements. /// /// Invalidates all indices with respect to `self`. /// /// :param: `keepCapacity`, if `true`, prevents the release of /// allocated storage, which can be a useful optimization /// when `self` is going to be grown again. mutating func removeAll(keepCapacity: Bool) } extension String.UTF16View.Index : BidirectionalIndexType { typealias Distance = Int func successor() -> String.UTF16View.Index func predecessor() -> String.UTF16View.Index } extension String.UTF16View.Index : Comparable { } extension String.UTF16View.Index { /// Construct the position in `utf16` that corresponds exactly to /// `utf8Index`. If no such position exists, the result is `nil`. /// /// Requires: `utf8Index` is an element of /// `indices(String(utf16)!.utf8)`. init?(_ utf8Index: UTF8Index, within utf16: String.UTF16View) /// Construct the position in `utf16` that corresponds exactly to /// `unicodeScalarIndex`. /// /// Requires: `unicodeScalarIndex` is an element of /// `indices(String(utf16)!.unicodeScalars)`. init(_ unicodeScalarIndex: UnicodeScalarIndex, within utf16: String.UTF16View) /// Construct the position in `utf16` that corresponds exactly to /// `characterIndex`. /// /// Requires: `characterIndex` is an element of /// `indices(String(utf16)!)`. init(_ characterIndex: String.Index, within utf16: String.UTF16View) /// Return the position in `utf8` that corresponds exactly /// to `self`, or if no such position exists, `nil`. /// /// Requires: `self` is an element of /// `indices(String(utf8)!.utf16)`. func samePositionIn(utf8: String.UTF8View) -> String.UTF8View.Index? /// Return the position in `unicodeScalars` that corresponds exactly /// to `self`, or if no such position exists, `nil`. /// /// Requires: `self` is an element of /// `indices(String(unicodeScalars).utf16)`. func samePositionIn(unicodeScalars: String.UnicodeScalarView) -> UnicodeScalarIndex? /// Return the position in `characters` that corresponds exactly /// to `self`, or if no such position exists, `nil`. /// /// Requires: `self` is an element of `indices(characters.utf16)`. func samePositionIn(characters: String) -> String.Index? } extension String.UTF8View.Index { /// Construct the position in `utf8` that corresponds exactly to /// `utf16Index`. If no such position exists, the result is `nil`. /// /// Requires: `utf8Index` is an element of /// `indices(String(utf16)!.utf8)`. init?(_ utf16Index: UTF16Index, within utf8: String.UTF8View) /// Construct the position in `utf8` that corresponds exactly to /// `unicodeScalarIndex`. /// /// Requires: `unicodeScalarIndex` is an element of /// `indices(String(utf8)!.unicodeScalars)`. init(_ unicodeScalarIndex: UnicodeScalarIndex, within utf8: String.UTF8View) /// Construct the position in `utf8` that corresponds exactly to /// `characterIndex`. /// /// Requires: `characterIndex` is an element of /// `indices(String(utf8)!)`. init(_ characterIndex: String.Index, within utf8: String.UTF8View) /// Return the position in `utf16` that corresponds exactly /// to `self`, or if no such position exists, `nil`. /// /// Requires: `self` is an element of `indices(String(utf16)!.utf8)`. func samePositionIn(utf16: String.UTF16View) -> String.UTF16View.Index? /// Return the position in `unicodeScalars` that corresponds exactly /// to `self`, or if no such position exists, `nil`. /// /// Requires: `self` is an element of /// `indices(String(unicodeScalars).utf8)`. func samePositionIn(unicodeScalars: String.UnicodeScalarView) -> UnicodeScalarIndex? /// Return the position in `characters` that corresponds exactly /// to `self`, or if no such position exists, `nil`. /// /// Requires: `self` is an element of `indices(characters.utf8)`. func samePositionIn(characters: String) -> String.Index? } extension String.UnicodeScalarView.Index { /// Construct the position in `unicodeScalars` that corresponds exactly to /// `utf16Index`. If no such position exists, the result is `nil`. /// /// Requires: `utf16Index` is an element of /// `indices(String(unicodeScalars).utf16)`. init?(_ utf16Index: UTF16Index, within unicodeScalars: String.UnicodeScalarView) /// Construct the position in `unicodeScalars` that corresponds exactly to /// `utf8Index`. If no such position exists, the result is `nil`. /// /// Requires: `utf8Index` is an element of /// `indices(String(unicodeScalars).utf8)`. init?(_ utf8Index: UTF8Index, within unicodeScalars: String.UnicodeScalarView) /// Construct the position in `unicodeScalars` that corresponds /// exactly to `characterIndex`. /// /// Requires: `characterIndex` is an element of /// `indices(String(unicodeScalars))`. init(_ characterIndex: String.Index, within unicodeScalars: String.UnicodeScalarView) /// Return the position in `utf8` that corresponds exactly /// to `self`. /// /// Requires: `self` is an element of `indices(String(utf8)!)`. func samePositionIn(utf8: String.UTF8View) -> String.UTF8View.Index /// Return the position in `utf16` that corresponds exactly /// to `self`. /// /// Requires: `self` is an element of `indices(String(utf16)!)`. func samePositionIn(utf16: String.UTF16View) -> String.UTF16View.Index /// Return the position in `characters` that corresponds exactly /// to `self`, or if no such position exists, `nil`. /// /// Requires: `self` is an element of `indices(characters.unicodeScalars)`. func samePositionIn(characters: String) -> String.Index? } /// Conforming types can be initialized with string interpolations /// containing `\(`\ ...\ `)` clauses. protocol StringInterpolationConvertible { /// Create an instance by concatenating the elements of `strings` init(stringInterpolation strings: Self...) /// Create an instance containing `expr`\ 's `print` representation init<T>(stringInterpolationSegment expr: T) } /// Conforming types can be initialized with arbitrary string literals protocol StringLiteralConvertible : ExtendedGraphemeClusterLiteralConvertible { typealias StringLiteralType /// Create an instance initialized to `value`. init(stringLiteral value: StringLiteralType) } /// The default type for an otherwise-unconstrained string literal typealias StringLiteralType = String /// A 64-bit unsigned integer value /// type. struct UInt : UnsignedIntegerType { var value: Builtin.Int64 /// A type that can represent the number of steps between pairs of /// values. typealias Distance = Int /// Create an instance initialized to zero. init() init(_ v: Builtin.Word) /// Create an instance initialized to `value`. init(_ value: UInt) /// Creates an integer from its big-endian representation, changing the /// byte order if necessary. init(bigEndian value: UInt) /// Creates an integer from its little-endian representation, changing the /// byte order if necessary. init(littleEndian value: UInt) init(_builtinIntegerLiteral value: Builtin.Int2048) /// Create an instance initialized to `value`. init(integerLiteral value: UInt) /// Returns the big-endian representation of the integer, changing the /// byte order if necessary. var bigEndian: UInt { get } /// Returns the little-endian representation of the integer, changing the /// byte order if necessary. var littleEndian: UInt { get } /// Returns the current integer with the byte order swapped. var byteSwapped: UInt { get } static var max: UInt { get } static var min: UInt { get } } extension UInt : Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } extension UInt : Printable { /// A textual representation of `self`. var description: String { get } } extension UInt : RandomAccessIndexType { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> UInt /// Returns the previous consecutive value before `self`. /// /// Requires: the previous value is representable. func predecessor() -> UInt /// Return the minimum number of applications of `successor` or /// `predecessor` required to reach `other` from `self`. /// /// Complexity: O(1). func distanceTo(other: UInt) -> Distance /// Return `self` offset by `n` steps. /// /// :returns: If `n > 0`, the result of applying `successor` to /// `self` `n` times. If `n < 0`, the result of applying /// `predecessor` to `self` `-n` times. Otherwise, `self`. /// /// Complexity: O(1) func advancedBy(amount: Distance) -> UInt } extension UInt { /// Add `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func addWithOverflow(lhs: UInt, _ rhs: UInt) -> (UInt, overflow: Bool) /// Subtract `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func subtractWithOverflow(lhs: UInt, _ rhs: UInt) -> (UInt, overflow: Bool) /// Multiply `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func multiplyWithOverflow(lhs: UInt, _ rhs: UInt) -> (UInt, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// a result and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func divideWithOverflow(lhs: UInt, _ rhs: UInt) -> (UInt, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// the remainder and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func remainderWithOverflow(lhs: UInt, _ rhs: UInt) -> (UInt, overflow: Bool) /// Represent this number using Swift's widest native unsigned /// integer type. func toUIntMax() -> UIntMax /// Explicitly convert to `IntMax`, trapping on overflow (except in -Ounchecked builds). func toIntMax() -> IntMax } extension UInt { init(_ v: UInt8) init(_ v: Int8) init(_ v: UInt16) init(_ v: Int16) init(_ v: UInt32) init(_ v: Int32) init(_ v: UInt64) /// Construct a `UInt` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt64) init(_ v: Int64) /// Construct a `UInt` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int64) init(_ v: Int) /// Construct a `UInt` having the same memory representation as /// the `Int` `bitPattern`. No range or overflow checking /// occurs, and the resulting `UInt` may not have the same numeric /// value as `bitPattern`--it is only guaranteed to use the same /// pattern of bits. init(bitPattern: Int) } extension UInt : BitwiseOperationsType { /// The empty bitset of type UInt. static var allZeros: UInt { get } } extension UInt { /// Construct an instance that approximates `other`. init(_ other: Float) /// Construct an instance that approximates `other`. init(_ other: Double) /// Construct an instance that approximates `other`. init(_ other: Float80) } extension UInt : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension UInt : CVarArgType { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// A 16-bit unsigned integer value /// type. struct UInt16 : UnsignedIntegerType { var value: Builtin.Int16 /// A type that can represent the number of steps between pairs of /// values. typealias Distance = Int /// Create an instance initialized to zero. init() /// Create an instance initialized to `value`. init(_ value: UInt16) /// Creates an integer from its big-endian representation, changing the /// byte order if necessary. init(bigEndian value: UInt16) /// Creates an integer from its little-endian representation, changing the /// byte order if necessary. init(littleEndian value: UInt16) init(_builtinIntegerLiteral value: Builtin.Int2048) /// Create an instance initialized to `value`. init(integerLiteral value: UInt16) /// Returns the big-endian representation of the integer, changing the /// byte order if necessary. var bigEndian: UInt16 { get } /// Returns the little-endian representation of the integer, changing the /// byte order if necessary. var littleEndian: UInt16 { get } /// Returns the current integer with the byte order swapped. var byteSwapped: UInt16 { get } static var max: UInt16 { get } static var min: UInt16 { get } } extension UInt16 : Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } extension UInt16 : Printable { /// A textual representation of `self`. var description: String { get } } extension UInt16 : RandomAccessIndexType { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> UInt16 /// Returns the previous consecutive value before `self`. /// /// Requires: the previous value is representable. func predecessor() -> UInt16 /// Return the minimum number of applications of `successor` or /// `predecessor` required to reach `other` from `self`. /// /// Complexity: O(1). func distanceTo(other: UInt16) -> Distance /// Return `self` offset by `n` steps. /// /// :returns: If `n > 0`, the result of applying `successor` to /// `self` `n` times. If `n < 0`, the result of applying /// `predecessor` to `self` `-n` times. Otherwise, `self`. /// /// Complexity: O(1) func advancedBy(amount: Distance) -> UInt16 } extension UInt16 { /// Add `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func addWithOverflow(lhs: UInt16, _ rhs: UInt16) -> (UInt16, overflow: Bool) /// Subtract `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func subtractWithOverflow(lhs: UInt16, _ rhs: UInt16) -> (UInt16, overflow: Bool) /// Multiply `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func multiplyWithOverflow(lhs: UInt16, _ rhs: UInt16) -> (UInt16, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// a result and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func divideWithOverflow(lhs: UInt16, _ rhs: UInt16) -> (UInt16, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// the remainder and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func remainderWithOverflow(lhs: UInt16, _ rhs: UInt16) -> (UInt16, overflow: Bool) /// Represent this number using Swift's widest native unsigned /// integer type. func toUIntMax() -> UIntMax /// Explicitly convert to `IntMax`. func toIntMax() -> IntMax } extension UInt16 { init(_ v: UInt8) init(_ v: Int8) init(_ v: Int16) init(_ v: UInt32) /// Construct a `UInt16` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt32) init(_ v: Int32) /// Construct a `UInt16` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int32) init(_ v: UInt64) /// Construct a `UInt16` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt64) init(_ v: Int64) /// Construct a `UInt16` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int64) init(_ v: UInt) /// Construct a `UInt16` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt) init(_ v: Int) /// Construct a `UInt16` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int) /// Construct a `UInt16` having the same memory representation as /// the `Int16` `bitPattern`. No range or overflow checking /// occurs, and the resulting `UInt16` may not have the same numeric /// value as `bitPattern`--it is only guaranteed to use the same /// pattern of bits. init(bitPattern: Int16) } extension UInt16 : BitwiseOperationsType { /// The empty bitset of type UInt16. static var allZeros: UInt16 { get } } extension UInt16 { /// Construct an instance that approximates `other`. init(_ other: Float) /// Construct an instance that approximates `other`. init(_ other: Double) /// Construct an instance that approximates `other`. init(_ other: Float80) } extension UInt16 : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension UInt16 : _StringElementType { } extension UInt16 : CVarArgType { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// A 32-bit unsigned integer value /// type. struct UInt32 : UnsignedIntegerType { var value: Builtin.Int32 /// A type that can represent the number of steps between pairs of /// values. typealias Distance = Int /// Create an instance initialized to zero. init() /// Create an instance initialized to `value`. init(_ value: UInt32) /// Creates an integer from its big-endian representation, changing the /// byte order if necessary. init(bigEndian value: UInt32) /// Creates an integer from its little-endian representation, changing the /// byte order if necessary. init(littleEndian value: UInt32) init(_builtinIntegerLiteral value: Builtin.Int2048) /// Create an instance initialized to `value`. init(integerLiteral value: UInt32) /// Returns the big-endian representation of the integer, changing the /// byte order if necessary. var bigEndian: UInt32 { get } /// Returns the little-endian representation of the integer, changing the /// byte order if necessary. var littleEndian: UInt32 { get } /// Returns the current integer with the byte order swapped. var byteSwapped: UInt32 { get } static var max: UInt32 { get } static var min: UInt32 { get } } extension UInt32 : Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } extension UInt32 : Printable { /// A textual representation of `self`. var description: String { get } } extension UInt32 : RandomAccessIndexType { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> UInt32 /// Returns the previous consecutive value before `self`. /// /// Requires: the previous value is representable. func predecessor() -> UInt32 /// Return the minimum number of applications of `successor` or /// `predecessor` required to reach `other` from `self`. /// /// Complexity: O(1). func distanceTo(other: UInt32) -> Distance /// Return `self` offset by `n` steps. /// /// :returns: If `n > 0`, the result of applying `successor` to /// `self` `n` times. If `n < 0`, the result of applying /// `predecessor` to `self` `-n` times. Otherwise, `self`. /// /// Complexity: O(1) func advancedBy(amount: Distance) -> UInt32 } extension UInt32 { /// Add `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func addWithOverflow(lhs: UInt32, _ rhs: UInt32) -> (UInt32, overflow: Bool) /// Subtract `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func subtractWithOverflow(lhs: UInt32, _ rhs: UInt32) -> (UInt32, overflow: Bool) /// Multiply `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func multiplyWithOverflow(lhs: UInt32, _ rhs: UInt32) -> (UInt32, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// a result and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func divideWithOverflow(lhs: UInt32, _ rhs: UInt32) -> (UInt32, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// the remainder and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func remainderWithOverflow(lhs: UInt32, _ rhs: UInt32) -> (UInt32, overflow: Bool) /// Represent this number using Swift's widest native unsigned /// integer type. func toUIntMax() -> UIntMax /// Explicitly convert to `IntMax`. func toIntMax() -> IntMax } extension UInt32 { init(_ v: UInt8) init(_ v: Int8) init(_ v: UInt16) init(_ v: Int16) init(_ v: Int32) init(_ v: UInt64) /// Construct a `UInt32` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt64) init(_ v: Int64) /// Construct a `UInt32` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int64) init(_ v: UInt) /// Construct a `UInt32` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt) init(_ v: Int) /// Construct a `UInt32` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int) /// Construct a `UInt32` having the same memory representation as /// the `Int32` `bitPattern`. No range or overflow checking /// occurs, and the resulting `UInt32` may not have the same numeric /// value as `bitPattern`--it is only guaranteed to use the same /// pattern of bits. init(bitPattern: Int32) } extension UInt32 : BitwiseOperationsType { /// The empty bitset of type UInt32. static var allZeros: UInt32 { get } } extension UInt32 { /// Construct an instance that approximates `other`. init(_ other: Float) /// Construct an instance that approximates `other`. init(_ other: Double) /// Construct an instance that approximates `other`. init(_ other: Float80) } extension UInt32 : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension UInt32 { /// Construct with value `v.value`. /// /// Requires: `v.value` can be represented as UInt32. init(_ v: UnicodeScalar) } extension UInt32 : CVarArgType { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// A 64-bit unsigned integer value /// type. struct UInt64 : UnsignedIntegerType { var value: Builtin.Int64 /// A type that can represent the number of steps between pairs of /// values. typealias Distance = Int /// Create an instance initialized to zero. init() /// Create an instance initialized to `value`. init(_ value: UInt64) /// Creates an integer from its big-endian representation, changing the /// byte order if necessary. init(bigEndian value: UInt64) /// Creates an integer from its little-endian representation, changing the /// byte order if necessary. init(littleEndian value: UInt64) init(_builtinIntegerLiteral value: Builtin.Int2048) /// Create an instance initialized to `value`. init(integerLiteral value: UInt64) /// Returns the big-endian representation of the integer, changing the /// byte order if necessary. var bigEndian: UInt64 { get } /// Returns the little-endian representation of the integer, changing the /// byte order if necessary. var littleEndian: UInt64 { get } /// Returns the current integer with the byte order swapped. var byteSwapped: UInt64 { get } static var max: UInt64 { get } static var min: UInt64 { get } } extension UInt64 : Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } extension UInt64 : Printable { /// A textual representation of `self`. var description: String { get } } extension UInt64 : RandomAccessIndexType { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> UInt64 /// Returns the previous consecutive value before `self`. /// /// Requires: the previous value is representable. func predecessor() -> UInt64 /// Return the minimum number of applications of `successor` or /// `predecessor` required to reach `other` from `self`. /// /// Complexity: O(1). func distanceTo(other: UInt64) -> Distance /// Return `self` offset by `n` steps. /// /// :returns: If `n > 0`, the result of applying `successor` to /// `self` `n` times. If `n < 0`, the result of applying /// `predecessor` to `self` `-n` times. Otherwise, `self`. /// /// Complexity: O(1) func advancedBy(amount: Distance) -> UInt64 } extension UInt64 { /// Add `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func addWithOverflow(lhs: UInt64, _ rhs: UInt64) -> (UInt64, overflow: Bool) /// Subtract `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func subtractWithOverflow(lhs: UInt64, _ rhs: UInt64) -> (UInt64, overflow: Bool) /// Multiply `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func multiplyWithOverflow(lhs: UInt64, _ rhs: UInt64) -> (UInt64, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// a result and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func divideWithOverflow(lhs: UInt64, _ rhs: UInt64) -> (UInt64, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// the remainder and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func remainderWithOverflow(lhs: UInt64, _ rhs: UInt64) -> (UInt64, overflow: Bool) /// Represent this number using Swift's widest native unsigned /// integer type. func toUIntMax() -> UIntMax /// Explicitly convert to `IntMax`, trapping on overflow (except in -Ounchecked builds). func toIntMax() -> IntMax } extension UInt64 { init(_ v: UInt8) init(_ v: Int8) init(_ v: UInt16) init(_ v: Int16) init(_ v: UInt32) init(_ v: Int32) init(_ v: Int64) init(_ v: UInt) init(_ v: Int) /// Construct a `UInt64` having the same memory representation as /// the `Int64` `bitPattern`. No range or overflow checking /// occurs, and the resulting `UInt64` may not have the same numeric /// value as `bitPattern`--it is only guaranteed to use the same /// pattern of bits. init(bitPattern: Int64) } extension UInt64 : BitwiseOperationsType { /// The empty bitset of type UInt64. static var allZeros: UInt64 { get } } extension UInt64 { /// Construct an instance that approximates `other`. init(_ other: Float) /// Construct an instance that approximates `other`. init(_ other: Double) /// Construct an instance that approximates `other`. init(_ other: Float80) } extension UInt64 : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension UInt64 { /// Construct with value `v.value`. /// /// Requires: `v.value` can be represented as UInt64. init(_ v: UnicodeScalar) } extension UInt64 : CVarArgType { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// A 8-bit unsigned integer value /// type. struct UInt8 : UnsignedIntegerType { var value: Builtin.Int8 /// A type that can represent the number of steps between pairs of /// values. typealias Distance = Int /// Create an instance initialized to zero. init() /// Create an instance initialized to `value`. init(_ value: UInt8) init(_builtinIntegerLiteral value: Builtin.Int2048) /// Create an instance initialized to `value`. init(integerLiteral value: UInt8) static var max: UInt8 { get } static var min: UInt8 { get } } extension UInt8 : Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } extension UInt8 : Printable { /// A textual representation of `self`. var description: String { get } } extension UInt8 : RandomAccessIndexType { /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> UInt8 /// Returns the previous consecutive value before `self`. /// /// Requires: the previous value is representable. func predecessor() -> UInt8 /// Return the minimum number of applications of `successor` or /// `predecessor` required to reach `other` from `self`. /// /// Complexity: O(1). func distanceTo(other: UInt8) -> Distance /// Return `self` offset by `n` steps. /// /// :returns: If `n > 0`, the result of applying `successor` to /// `self` `n` times. If `n < 0`, the result of applying /// `predecessor` to `self` `-n` times. Otherwise, `self`. /// /// Complexity: O(1) func advancedBy(amount: Distance) -> UInt8 } extension UInt8 { /// Add `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func addWithOverflow(lhs: UInt8, _ rhs: UInt8) -> (UInt8, overflow: Bool) /// Subtract `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func subtractWithOverflow(lhs: UInt8, _ rhs: UInt8) -> (UInt8, overflow: Bool) /// Multiply `lhs` and `rhs`, returning a result and a /// `Bool` that is true iff the operation caused an arithmetic /// overflow. static func multiplyWithOverflow(lhs: UInt8, _ rhs: UInt8) -> (UInt8, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// a result and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func divideWithOverflow(lhs: UInt8, _ rhs: UInt8) -> (UInt8, overflow: Bool) /// Divide `lhs` and `rhs`, returning /// the remainder and a `Bool` /// that is true iff the operation caused an arithmetic overflow. static func remainderWithOverflow(lhs: UInt8, _ rhs: UInt8) -> (UInt8, overflow: Bool) /// Represent this number using Swift's widest native unsigned /// integer type. func toUIntMax() -> UIntMax /// Explicitly convert to `IntMax`. func toIntMax() -> IntMax } extension UInt8 { init(_ v: Int8) init(_ v: UInt16) /// Construct a `UInt8` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt16) init(_ v: Int16) /// Construct a `UInt8` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int16) init(_ v: UInt32) /// Construct a `UInt8` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt32) init(_ v: Int32) /// Construct a `UInt8` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int32) init(_ v: UInt64) /// Construct a `UInt8` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt64) init(_ v: Int64) /// Construct a `UInt8` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int64) init(_ v: UInt) /// Construct a `UInt8` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: UInt) init(_ v: Int) /// Construct a `UInt8` having the same bitwise representation as /// the least significant bits of the provided bit pattern. /// /// No range or overflow checking occurs. init(truncatingBitPattern: Int) /// Construct a `UInt8` having the same memory representation as /// the `Int8` `bitPattern`. No range or overflow checking /// occurs, and the resulting `UInt8` may not have the same numeric /// value as `bitPattern`--it is only guaranteed to use the same /// pattern of bits. init(bitPattern: Int8) } extension UInt8 : BitwiseOperationsType { /// The empty bitset of type UInt8. static var allZeros: UInt8 { get } } extension UInt8 { /// Construct an instance that approximates `other`. init(_ other: Float) /// Construct an instance that approximates `other`. init(_ other: Double) /// Construct an instance that approximates `other`. init(_ other: Float80) } extension UInt8 : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension UInt8 : _StringElementType { } extension UInt8 { /// Construct with value `v.value`. /// /// Requires: `v.value` can be represented as ASCII (0..<128). init(ascii v: UnicodeScalar) } extension UInt8 : CVarArgType { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// The largest native unsigned integer type typealias UIntMax = UInt64 /// A codec for `UTF-16 <http://www.unicode.org/glossary/#UTF_16>`_. struct UTF16 : UnicodeCodecType { /// A type that can hold `code unit /// <http://www.unicode.org/glossary/#code_unit>`_ values for this /// encoding. typealias CodeUnit = UInt16 init() /// Start or continue decoding a UTF sequence. /// /// In order to decode a code unit sequence completely, this function should /// be called repeatedly until it returns `UnicodeDecodingResult.EmptyInput`. /// Checking that the generator was exhausted is not sufficient. The decoder /// can have an internal buffer that is pre-filled with data from the input /// generator. /// /// Because of buffering, it is impossible to find the corresponing position /// in the generator for a given returned `UnicodeScalar` or an error. /// /// :param: `next`: a *generator* of code units to be decoded. mutating func decode<G : GeneratorType where CodeUnit == CodeUnit>(inout input: G) -> UnicodeDecodingResult /// Encode a `UnicodeScalar` as a series of `CodeUnit`\ s by /// `put`'ing each `CodeUnit` to `output`. static func encode<S : SinkType where CodeUnit == CodeUnit>(input: UnicodeScalar, inout output: S) } extension UTF16 { /// Return the number of code units required to encode `x`. static func width(x: UnicodeScalar) -> Int /// Return the high surrogate code unit of a `surrogate pair /// <http://www.unicode.org/glossary/#surrogate_pair>`_ representing /// `x`. /// /// Requires: `width(x) == 2` static func leadSurrogate(x: UnicodeScalar) -> CodeUnit /// Return the low surrogate code unit of a `surrogate pair /// <http://www.unicode.org/glossary/#surrogate_pair>`_ representing /// `x`. /// /// Requires: `width(x) == 2` static func trailSurrogate(x: UnicodeScalar) -> CodeUnit static func isLeadSurrogate(x: CodeUnit) -> Bool static func isTrailSurrogate(x: CodeUnit) -> Bool /// Returns the number of UTF-16 code units required for the given code unit /// sequence when transcoded to UTF-16, and a bit describing if the sequence /// was found to contain only ASCII characters. /// /// If `repairIllFormedSequences` is `true`, the function always succeeds. /// If it is `false`, `nil` is returned if an ill-formed code unit sequence is /// found in `input`. static func measure<Encoding : UnicodeCodecType, Input : GeneratorType where Encoding.CodeUnit == Encoding.CodeUnit>(_: Encoding.Type, input: Input, repairIllFormedSequences: Bool) -> (Int, Bool)? } /// A codec for `UTF-32 <http://www.unicode.org/glossary/#UTF_32>`_. struct UTF32 : UnicodeCodecType { /// A type that can hold `code unit /// <http://www.unicode.org/glossary/#code_unit>`_ values for this /// encoding. typealias CodeUnit = UInt32 init() /// Start or continue decoding a UTF sequence. /// /// In order to decode a code unit sequence completely, this function should /// be called repeatedly until it returns `UnicodeDecodingResult.EmptyInput`. /// Checking that the generator was exhausted is not sufficient. The decoder /// can have an internal buffer that is pre-filled with data from the input /// generator. /// /// Because of buffering, it is impossible to find the corresponing position /// in the generator for a given returned `UnicodeScalar` or an error. /// /// :param: `next`: a *generator* of code units to be decoded. mutating func decode<G : GeneratorType where CodeUnit == CodeUnit>(inout input: G) -> UnicodeDecodingResult /// Encode a `UnicodeScalar` as a series of `CodeUnit`\ s by /// `put`'ing each `CodeUnit` to `output`. static func encode<S : SinkType where CodeUnit == CodeUnit>(input: UnicodeScalar, inout output: S) } /// A codec for `UTF-8 <http://www.unicode.org/glossary/#UTF_8>`_. struct UTF8 : UnicodeCodecType { /// A type that can hold `code unit /// <http://www.unicode.org/glossary/#code_unit>`_ values for this /// encoding. typealias CodeUnit = UInt8 init() /// Start or continue decoding a UTF sequence. /// /// In order to decode a code unit sequence completely, this function should /// be called repeatedly until it returns `UnicodeDecodingResult.EmptyInput`. /// Checking that the generator was exhausted is not sufficient. The decoder /// can have an internal buffer that is pre-filled with data from the input /// generator. /// /// Because of buffering, it is impossible to find the corresponing position /// in the generator for a given returned `UnicodeScalar` or an error. /// /// :param: `next`: a *generator* of code units to be decoded. mutating func decode<G : GeneratorType where CodeUnit == CodeUnit>(inout next: G) -> UnicodeDecodingResult /// Encode a `UnicodeScalar` as a series of `CodeUnit`\ s by /// `put`'ing each `CodeUnit` to `output`. static func encode<S : SinkType where CodeUnit == CodeUnit>(input: UnicodeScalar, inout output: S) /// Return true if `byte` is a continuation byte of the form /// `0b10xxxxxx` static func isContinuation(byte: CodeUnit) -> Bool } /// An unsigned integer type that occupies one machine word typealias UWord = UInt /// A Unicode `encoding scheme /// <http://www.unicode.org/glossary/#character_encoding_scheme>`_ /// /// Consists of an underlying `code unit /// <http://www.unicode.org/glossary/#code_unit>`_ and functions to /// translate between sequences of these code units and `unicode /// scalar values /// <http://www.unicode.org/glossary/#unicode_scalar_value>`_. protocol UnicodeCodecType { /// A type that can hold `code unit /// <http://www.unicode.org/glossary/#code_unit>`_ values for this /// encoding. typealias CodeUnit init() /// Start or continue decoding a UTF sequence. /// /// In order to decode a code unit sequence completely, this function should /// be called repeatedly until it returns `UnicodeDecodingResult.EmptyInput`. /// Checking that the generator was exhausted is not sufficient. The decoder /// can have an internal buffer that is pre-filled with data from the input /// generator. /// /// Because of buffering, it is impossible to find the corresponing position /// in the generator for a given returned `UnicodeScalar` or an error. /// /// :param: `next`: a *generator* of code units to be decoded. mutating func decode<G : GeneratorType where Self.CodeUnit == CodeUnit>(inout next: G) -> UnicodeDecodingResult /// Encode a `UnicodeScalar` as a series of `CodeUnit`\ s by /// `put`'ing each `CodeUnit` to `output`. static func encode<S : SinkType where Self.CodeUnit == CodeUnit>(input: UnicodeScalar, inout output: S) } /// The result of one Unicode decoding step /// /// A unicode scalar value, an indication that no more unicode scalars /// are available, or an indication of a decoding error. enum UnicodeDecodingResult { case Result(UnicodeScalar) case EmptyInput case Error /// Return true if `self` indicates no more unicode scalars are /// available. func isEmptyInput() -> Bool } /// A `Unicode scalar value /// <http://www.unicode.org/glossary/#unicode_scalar_value>`_. struct UnicodeScalar : UnicodeScalarLiteralConvertible { /// A numeric representation of `self`. var value: UInt32 { get } init(_builtinUnicodeScalarLiteral value: Builtin.Int32) /// Create an instance initialized to `value`. init(unicodeScalarLiteral value: UnicodeScalar) /// Creates an instance of the NUL scalar value. init() /// Create an instance with numeric value `v`. /// /// Requires: `v` is a valid Unicode scalar value. init(_ v: UInt32) /// Create an instance with numeric value `v`. /// /// Requires: `v` is a valid Unicode scalar value. init(_ v: UInt16) /// Create an instance with numeric value `v`. init(_ v: UInt8) /// Create a duplicate of `v`. init(_ v: UnicodeScalar) /// Return a String representation of `self` . /// /// :param: `asASCII`, if `true`, forces most values into a numeric /// representation. func escape(#asASCII: Bool) -> String /// Returns true if this is an ASCII character (code point 0 to 127 /// inclusive). func isASCII() -> Bool } extension UnicodeScalar : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension UnicodeScalar : Streamable { /// Write a textual representation of `self` into `target` func writeTo<Target : OutputStreamType>(inout target: Target) } extension UnicodeScalar : Printable, DebugPrintable { /// A textual representation of `self`. var description: String { get } /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } extension UnicodeScalar : Hashable { /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } } extension UnicodeScalar { /// Construct with value `v`. /// /// Requires: `v` is a valid unicode scalar value. init(_ v: Int) } extension UnicodeScalar : Comparable { } extension UnicodeScalar { } extension UnicodeScalar.UTF16View : CollectionType { } /// Conforming types can be initialized with string literals /// containing a single `Unicode scalar value /// <http://www.unicode.org/glossary/#unicode_scalar_value>`_. protocol UnicodeScalarLiteralConvertible { typealias UnicodeScalarLiteralType /// Create an instance initialized to `value`. init(unicodeScalarLiteral value: UnicodeScalarLiteralType) } /// The default type for an otherwise-unconstrained unicode scalar literal typealias UnicodeScalarType = String /// A type for propagating an unmanaged object reference. /// /// When you use this type, you become partially responsible for /// keeping the object alive. struct Unmanaged<T> { /// Unsafely turn an opaque C pointer into an unmanaged /// class reference. /// /// This operation does not change reference counts. /// /// :: /// /// let str: CFString = Unmanaged.fromOpaque(ptr).takeUnretainedValue() static func fromOpaque(value: COpaquePointer) -> Unmanaged<T> /// Unsafely turn an unmanaged class reference into an opaque /// C pointer. /// /// This operation does not change reference counts. /// /// :: /// /// let str: CFString = Unmanaged.fromOpaque(ptr).takeUnretainedValue() func toOpaque() -> COpaquePointer /// Create an unmanaged reference with an unbalanced retain. /// The object will leak if nothing eventually balances the retain. /// /// This is useful when passing an object to an API which Swift /// does not know the ownership rules for, but you know that the /// API expects you to pass the object at +1. static func passRetained(value: T) -> Unmanaged<T> /// Create an unmanaged reference without performing an unbalanced /// retain. /// /// This is useful when passing a reference to an API which Swift /// does not know the ownership rules for, but you know that the /// API expects you to pass the object at +0. /// /// :: /// /// CFArraySetValueAtIndex(.passUnretained(array), i, /// .passUnretained(object)) static func passUnretained(value: T) -> Unmanaged<T> /// Get the value of this unmanaged reference as a managed /// reference without consuming an unbalanced retain of it. /// /// This is useful when a function returns an unmanaged reference /// and you know that you're not responsible for releasing the result. func takeUnretainedValue() -> T /// Get the value of this unmanaged reference as a managed /// reference and consume an unbalanced retain of it. /// /// This is useful when a function returns an unmanaged reference /// and you know that you're responsible for releasing the result. func takeRetainedValue() -> T /// Perform an unbalanced retain of the object. func retain() -> Unmanaged<T> /// Perform an unbalanced release of the object. func release() /// Perform an unbalanced autorelease of the object. func autorelease() -> Unmanaged<T> } /// A non-owning pointer to buffer of `T`\ s stored /// contiguously in memory, presenting a `Collection` interface to the /// underlying elements. struct UnsafeBufferPointer<T> : CollectionType { /// Always zero, which is the index of the first element in a /// non-empty buffer. var startIndex: Int { get } /// The "past the end" position; always identical to `count`. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. var endIndex: Int { get } subscript (i: Int) -> T { get } /// Construct an UnsafePointer over the `count` contiguous /// `T` instances beginning at `start`. init(start: UnsafePointer<T>, count: Int) /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> UnsafeBufferPointerGenerator<T> /// A pointer to the first element of the buffer var baseAddress: UnsafePointer<T> { get } /// The number of elements in the buffer var count: Int { get } } extension UnsafeBufferPointer : DebugPrintable { /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } /// A generator for the elements in the buffer referenced by /// `UnsafeBufferPointer` or `UnsafeMutableBufferPointer` struct UnsafeBufferPointerGenerator<T> : GeneratorType, SequenceType { /// Advance to the next element and return it, or `nil` if no next /// element exists. mutating func next() -> T? /// `UnsafeBufferPointerGenerator` is also a `SequenceType`, so it /// `generate`\ 's a copy of itself func generate() -> UnsafeBufferPointerGenerator<T> } /// A non-owning pointer to buffer of mutable `T`\ s stored /// contiguously in memory, presenting a `Collection` interface to the /// underlying elements. struct UnsafeMutableBufferPointer<T> : MutableCollectionType { /// Always zero, which is the index of the first element in a /// non-empty buffer. var startIndex: Int { get } /// The "past the end" position; always identical to `count`. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. var endIndex: Int { get } subscript (i: Int) -> T { get nonmutating set } /// Construct an UnsafeMutablePointer over the `count` contiguous /// `T` instances beginning at `start`. init(start: UnsafeMutablePointer<T>, count: Int) /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> UnsafeBufferPointerGenerator<T> /// A pointer to the first element of the buffer var baseAddress: UnsafeMutablePointer<T> { get } /// The number of elements in the buffer var count: Int { get } } extension UnsafeMutableBufferPointer : DebugPrintable { /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } /// A pointer to an object of type `T`. This type provides no automated /// memory management, and therefore the user must take care to allocate /// and free memory appropriately. /// /// The pointer can be in one of the following states: /// /// - memory is not allocated (for example, pointer is null, or memory has /// been deallocated previously); /// /// - memory is allocated, but value has not been initialized; /// /// - memory is allocated and value is initialized. struct UnsafeMutablePointer<T> : RandomAccessIndexType, Hashable, NilLiteralConvertible, _PointerType { /// Construct a null pointer. init() /// Convert from an opaque C pointer to a typed pointer /// /// This is a fundamentally unsafe conversion. init(_ other: COpaquePointer) /// Construct an `UnsafeMutablePointer` from a given address in memory. /// /// This is a fundamentally unsafe conversion. init(bitPattern: Word) /// Construct an `UnsafeMutablePointer` from a given address in memory. /// /// This is a fundamentally unsafe conversion. init(bitPattern: UWord) /// Convert from an UnsafeMutablePointer of a different type. /// /// This is a fundamentally unsafe conversion. init<U>(_ from: UnsafeMutablePointer<U>) /// Convert from a UnsafePointer of a different type. /// /// This is a fundamentally unsafe conversion. init<U>(_ from: UnsafePointer<U>) /// Create an instance initialized with `nil`. init(nilLiteral: ()) /// Allocate memory for `num` objects of type `T`. /// /// Postcondition: the memory is allocated, but not initialized. static func alloc(num: Int) -> UnsafeMutablePointer<T> /// Deallocate `num` objects. /// /// :param: num number of objects to deallocate. Should match exactly /// the value that was passed to `alloc()` (partial deallocations are not /// possible). /// /// Precondition: the memory is not initialized. /// /// Postcondition: the memory has been deallocated. func dealloc(num: Int) /// Access the underlying raw memory, getting and /// setting values. var memory: T { get nonmutating set } /// Initialize the value the pointer points to, to construct /// an object where there was no object previously stored. /// /// Precondition: the memory is not initialized. /// /// Postcondition: the memory is initalized; the value should eventually /// be destroyed or moved from to avoid leaks. func initialize(newvalue: T) /// Retrieve the value the pointer points to, moving it away /// from the location referenced in memory. /// /// Equivalent to reading `memory` property and calling `destroy()`, /// but more efficient. /// /// Precondition: the memory is initialized. /// /// Postcondition: the value has been destroyed and the memory must /// be initialized before being used again. func move() -> T /// Assign from `count` values beginning at source into initialized /// memory, proceeding from the first element to the last. func assignFrom(source: UnsafeMutablePointer<T>, count: Int) /// Assign from `count` values beginning at `source` into /// initialized memory, proceeding from the last value to the first. /// Use this for assigning ranges into later memory that may overlap /// with the source range. /// /// Requires: either `source` precedes `self` or follows `self + count`. func assignBackwardFrom(source: UnsafeMutablePointer<T>, count: Int) /// Move count values beginning at source into raw memory, /// transforming the source values into raw memory. func moveInitializeFrom(source: UnsafeMutablePointer<T>, count: Int) /// Move `count` values beginning at `source` into uninitialized memory, /// transforming the source values into raw memory, proceeding from /// the last value to the first. Use this for copying ranges into /// later memory that may overlap with the source range. /// /// Requires: either `source` precedes `self` or follows `self + count`. func moveInitializeBackwardFrom(source: UnsafeMutablePointer<T>, count: Int) /// Copy count values beginning at source into raw memory. /// /// Precondition: the memory is not initialized. /// /// Requires: `self` and `source` may not overlap. func initializeFrom(source: UnsafeMutablePointer<T>, count: Int) /// Copy the elements of `C` into raw memory. /// /// Precondition: the memory is not initialized. func initializeFrom<C : CollectionType>(source: C) /// Assign from `count` values beginning at `source` into initialized /// memory, transforming the source values into raw memory. /// /// Requires: the `self` and `source` ranges may not overlap. func moveAssignFrom(source: UnsafeMutablePointer<T>, count: Int) /// Destroy the object the pointer points to. /// /// Precondition: the memory is initialized. /// /// Postcondition: the value has been destroyed and the memory must /// be initialized before being used again. func destroy() /// Destroy the `count` objects the pointer points to. /// Precondition: the memory is initialized. /// /// Postcondition: the value has been destroyed and the memory must /// be initialized before being used again. func destroy(count: Int) subscript (i: Int) -> T { get nonmutating set } /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> UnsafeMutablePointer<T> /// Returns the previous consecutive value before `self`. /// /// Requires: the previous value is representable. func predecessor() -> UnsafeMutablePointer<T> /// Return the minimum number of applications of `successor` or /// `predecessor` required to reach `other` from `self`. /// /// Complexity: O(1). func distanceTo(x: UnsafeMutablePointer<T>) -> Int /// Return `self` offset by `n` steps. /// /// :returns: If `n > 0`, the result of applying `successor` to /// `self` `n` times. If `n < 0`, the result of applying /// `predecessor` to `self` `-n` times. Otherwise, `self`. /// /// Complexity: O(1) func advancedBy(n: Int) -> UnsafeMutablePointer<T> } extension UnsafeMutablePointer : DebugPrintable { /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } extension UnsafeMutablePointer : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension UnsafeMutablePointer : SinkType { mutating func put(x: T) } extension UnsafeMutablePointer : CVarArgType { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// A pointer to an object of type `T`. This type provides no automated /// memory management, and therefore the user must take care to allocate /// and free memory appropriately. /// /// The pointer can be in one of the following states: /// /// - memory is not allocated (for example, pointer is null, or memory has /// been deallocated previously); /// /// - memory is allocated, but value has not been initialized; /// /// - memory is allocated and value is initialized. struct UnsafePointer<T> : RandomAccessIndexType, Hashable, NilLiteralConvertible, _PointerType { /// Construct a null pointer. init() /// Convert from an opaque C pointer to a typed pointer /// /// This is a fundamentally unsafe conversion. init(_ other: COpaquePointer) /// Construct an `UnsafePointer` from a given address in memory. /// /// This is a fundamentally unsafe conversion. init(bitPattern: Word) /// Construct an `UnsafePointer` from a given address in memory. /// /// This is a fundamentally unsafe conversion. init(bitPattern: UWord) /// Convert from an UnsafeMutablePointer of a different type. /// /// This is a fundamentally unsafe conversion. init<U>(_ from: UnsafeMutablePointer<U>) /// Convert from a UnsafePointer of a different type. /// /// This is a fundamentally unsafe conversion. init<U>(_ from: UnsafePointer<U>) /// Create an instance initialized with `nil`. init(nilLiteral: ()) /// Access the underlying raw memory, getting and /// setting values. var memory: T { get } subscript (i: Int) -> T { get } /// The hash value. /// /// **Axiom:** `x == y` implies `x.hashValue == y.hashValue` /// /// **Note:** the hash value is not guaranteed to be stable across /// different invocations of the same program. Do not persist the /// hash value across program runs. var hashValue: Int { get } /// Returns the next consecutive value after `self`. /// /// Requires: the next value is representable. func successor() -> UnsafePointer<T> /// Returns the previous consecutive value before `self`. /// /// Requires: the previous value is representable. func predecessor() -> UnsafePointer<T> /// Return the minimum number of applications of `successor` or /// `predecessor` required to reach `other` from `self`. /// /// Complexity: O(1). func distanceTo(x: UnsafePointer<T>) -> Int /// Return `self` offset by `n` steps. /// /// :returns: If `n > 0`, the result of applying `successor` to /// `self` `n` times. If `n < 0`, the result of applying /// `predecessor` to `self` `-n` times. Otherwise, `self`. /// /// Complexity: O(1) func advancedBy(n: Int) -> UnsafePointer<T> } extension UnsafePointer : DebugPrintable { /// A textual representation of `self`, suitable for debugging. var debugDescription: String { get } } extension UnsafePointer : Reflectable { /// Returns a mirror that reflects `self`. func getMirror() -> MirrorType } extension UnsafePointer : CVarArgType { /// Transform `self` into a series of machine words that can be /// appropriately interpreted by C varargs func encode() -> [Word] } /// A set of common requirements for Swift's unsigned integer types. protocol UnsignedIntegerType : _UnsignedIntegerType, IntegerType { } /// An object that can manage the lifetime of storage backing a /// `CVaListPointer` final class VaListBuilder { } /// A signed integer type that occupies one machine word typealias Word = Int /// A sequence of pairs built out of two underlying sequences, where /// the elements of the `i`\ th pair are the `i`\ th elements of each /// underlying sequence. struct Zip2<S0 : SequenceType, S1 : SequenceType> : SequenceType { typealias Stream1 = S0.Generator typealias Stream2 = S1.Generator /// A type whose instances can produce the elements of this /// sequence, in order. typealias Generator = ZipGenerator2<S0.Generator, S1.Generator> /// Construct an instance that makes pairs of elements from `s0` and /// `s1`. init(_ s0: S0, _ s1: S1) /// Return a *generator* over the elements of this *sequence*. /// /// Complexity: O(1) func generate() -> Generator } /// A generator for the `Zip2` sequence struct ZipGenerator2<E0 : GeneratorType, E1 : GeneratorType> : GeneratorType { /// The type of element returned by `next()`. typealias Element = (E0.Element, E1.Element) /// Construct around a pair of underlying generators. init(_ e0: E0, _ e1: E1) /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// Requires: `next()` has not been applied to a copy of `self` /// since the copy was made, and no preceding call to `self.next()` /// has returned `nil`. mutating func next() -> Element? } func ^(lhs: Int8, rhs: Int8) -> Int8 func ^(lhs: UInt8, rhs: UInt8) -> UInt8 func ^(lhs: Int16, rhs: Int16) -> Int16 func ^(lhs: UInt32, rhs: UInt32) -> UInt32 func ^<T : _RawOptionSetType>(a: T, b: T) -> T func ^(lhs: Int32, rhs: Int32) -> Int32 func ^(lhs: UInt64, rhs: UInt64) -> UInt64 func ^(lhs: UInt16, rhs: UInt16) -> UInt16 func ^(lhs: UInt, rhs: UInt) -> UInt func ^(lhs: Int, rhs: Int) -> Int func ^(lhs: Int64, rhs: Int64) -> Int64 func ^=(inout lhs: Int32, rhs: Int32) func ^=(inout lhs: UInt16, rhs: UInt16) func ^=<T : BitwiseOperationsType>(inout lhs: T, rhs: T) func ^=(inout lhs: Int, rhs: Int) func ^=(inout lhs: UInt, rhs: UInt) func ^=(inout lhs: Int64, rhs: Int64) func ^=(inout lhs: UInt64, rhs: UInt64) func ^=(inout lhs: UInt32, rhs: UInt32) func ^=(inout lhs: Int16, rhs: Int16) func ^=(inout lhs: Int8, rhs: Int8) func ^=(inout lhs: UInt8, rhs: UInt8) /// The underlying buffer for an ArrayType conforms to /// _ArrayBufferType. This buffer does not provide value semantics. protocol _ArrayBufferType : MutableCollectionType { /// The type of elements stored in the buffer typealias Element /// create an empty buffer init() /// Adopt the storage of x init(_ buffer: _ContiguousArrayBuffer<Element>) /// Copy the given subRange of this buffer into uninitialized memory /// starting at target. Return a pointer past-the-end of the /// just-initialized memory. func _uninitializedCopy(subRange: Range<Int>, target: UnsafeMutablePointer<Element>) -> UnsafeMutablePointer<Element> subscript (index: Int) -> Element { get nonmutating set } /// If this buffer is backed by a uniquely-referenced mutable /// _ContiguousArrayBuffer that can be grown in-place to allow the self /// buffer store minimumCapacity elements, returns that buffer. /// Otherwise, returns nil. Note: the result's baseAddress may /// not match ours, if we are a _SliceBuffer. /// /// Note: this function must remain mutating; otherwise the buffer /// may acquire spurious extra references, which will cause /// unnecessary reallocation. mutating func requestUniqueMutableBackingBuffer(minimumCapacity: Int) -> _ContiguousArrayBuffer<Element>? /// Returns true iff this buffer is backed by a uniquely-referenced mutable /// _ContiguousArrayBuffer. /// /// Note: this function must remain mutating; otherwise the buffer /// may acquire spurious extra references, which will cause /// unnecessary reallocation. mutating func isMutableAndUniquelyReferenced() -> Bool /// If this buffer is backed by a `_ContiguousArrayBuffer` /// containing the same number of elements as `self`, return it. /// Otherwise, return `nil`. func requestNativeBuffer() -> _ContiguousArrayBuffer<Element>? /// Replace the given subRange with the first newCount elements of /// the given collection. /// /// Requires: this buffer is backed by a uniquely-referenced /// _ContiguousArrayBuffer mutating func replace<C : CollectionType where Self.Element == Element>(#subRange: Range<Int>, with newCount: Int, elementsOf newValues: C) subscript (subRange: Range<Int>) -> _SliceBuffer<Element> { get } /// Call `body(p)`, where `p` is an `UnsafeBufferPointer` over the /// underlying contiguous storage. If no such storage exists, it is /// created on-demand. func withUnsafeBufferPointer<R>(body: @noescape (UnsafeBufferPointer<Element>) -> R) -> R /// Call `body(p)`, where `p` is an `UnsafeMutableBufferPointer` /// over the underlying contiguous storage. Requires: such /// contiguous storage exists or the buffer is empty mutating func withUnsafeMutableBufferPointer<R>(body: @noescape (UnsafeMutableBufferPointer<Element>) -> R) -> R /// How many elements the buffer stores var count: Int { get set } /// How many elements the buffer can store without reallocation var capacity: Int { get } /// An object that keeps the elements stored in this buffer alive var owner: AnyObject { get } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, nil. var baseAddress: UnsafeMutablePointer<Element> { get } /// A value that identifies the storage used by the buffer. Two /// buffers address the same elements when they have the same /// identity and count. var identity: UnsafePointer<Void> { get } } protocol _ArrayType : __ArrayType, RangeReplaceableCollectionType, MutableSliceable, ArrayLiteralConvertible { /// Construct an empty Array init() /// Construct an array of count elements, each initialized to repeatedValue init(count: Int, repeatedValue: Self.Generator.Element) /// How many elements the Array stores var count: Int { get } /// How many elements the Array can store without reallocation var capacity: Int { get } /// true if and only if the Array is empty var isEmpty: Bool { get } /// An object that guarantees the lifetime of this array's elements var _owner: AnyObject? { get } /// If the elements are stored contiguously, a pointer to the first /// element. Otherwise, nil. var _baseAddressIfContiguous: UnsafeMutablePointer<Self.Element> { get } subscript (index: Int) -> Self.Generator.Element { get set } /// Reserve enough space to store minimumCapacity elements. /// /// PostCondition: `capacity >= minimumCapacity` and the array has /// mutable contiguous storage. /// /// Complexity: O(`count`) mutating func reserveCapacity(minimumCapacity: Int) /// Append newElement to the Array in O(1) (amortized) mutating func append(newElement: Self.Generator.Element) /// Append elements from `sequence` to the Array mutating func extend<S : SequenceType where Self.Generator.Element == Self.Generator.Element>(sequence: S) /// Operator form of extend func +=<S : SequenceType where Self.Generator.Element == Self.Generator.Element>(inout lhs: Self, rhs: S) /// Remove an element from the end of the Array in O(1). Returns: /// the removed element. Requires: count > 0 mutating func removeLast() -> Self.Generator.Element /// Insert `newElement` at index `i`. /// /// Invalidates all indices with respect to `self`. /// /// Complexity: O(\ `count(self)`\ ). /// /// Requires: `atIndex` <= `count` mutating func insert(newElement: Self.Generator.Element, atIndex i: Int) /// Remove and return the element at the given index. Returns: the removed /// element. Worst case complexity: O(N). Requires: count > index mutating func removeAtIndex(index: Int) -> Self.Generator.Element /// Erase all the elements. If `keepCapacity` is `true`, `capacity` /// will not change mutating func removeAll(#keepCapacity: Bool) func join<S : SequenceType>(elements: S) -> Self func reduce<U>(initial: U, combine: @noescape (U, Self.Generator.Element) -> U) -> U /// Sort `self` in-place according to `isOrderedBefore`. Requires: /// `isOrderedBefore` induces a `strict weak ordering /// <http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings>`_ /// over the elements. mutating func sort(isOrderedBefore: (Self.Generator.Element, Self.Generator.Element) -> Bool) typealias _Buffer : _ArrayBufferType init(_ buffer: _Buffer) } /// This protocol is an implementation detail of `BidirectionalIndexType`; do /// not use it directly. /// /// Its requirements are inherited by `BidirectionalIndexType` and thus must /// be satisfied by types conforming to that protocol. protocol _BidirectionalIndexType : _ForwardIndexType { /// Return the previous consecutive value in a discrete sequence. /// /// If `self` has a well-defined successor, /// `self.successor().predecessor() == self`. If `self` has a /// well-defined predecessor, `self.predecessor().successor() == /// self`. /// /// Requires: `self` has a well-defined predecessor. func predecessor() -> Self } /// Floating point types need to be passed differently on x86_64 /// systems. CoreGraphics uses this to make CGFloat work properly. protocol _CVarArgPassedAsDouble : CVarArgType { } /// Effectively a proxy for NSString that doesn't mention it by /// name. NSString's conformance to this protocol is declared in /// Foundation. @objc protocol _CocoaStringType { } /// This protocol is an implementation detail of `CollectionType`; do /// not use it directly. /// /// Its requirements are inherited by `CollectionType` and thus must /// be satisfied by types conforming to that protocol. protocol _CollectionType : _SequenceType { /// 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. typealias Index : ForwardIndexType /// The position of the first element in a non-empty collection. /// /// Identical to `endIndex` in an empty collection. var startIndex: Index { get } /// 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()`. var endIndex: Index { get } typealias _Element subscript (_i: Index) -> _Element { get } } /// This protocol is an implementation detail of `Comparable`; do /// not use it directly. /// /// Its requirements are inherited by `Comparable` and thus must /// be satisfied by types conforming to that protocol. protocol _Comparable { /// A `strict total order /// <http://en.wikipedia.org/wiki/Total_order#Strict_total_order>`_ /// over instances of `Self` func <(lhs: Self, rhs: Self) -> Bool } /// A container is destructor safe if whether it may store to memory on /// destruction only depends on its type parameters. /// For example, whether Array<T> may store to memory on destruction depends /// only on T. /// If T is an Int we know the Array<Int> does not store to memory during /// destruction. If T is an arbitrary class Array<MemoryUnsafeDestructorClass> /// then the compiler will deduce may store to memory on destruction because /// MemoryUnsafeDestructorClass' destructor may store to memory on destruction. protocol _DestructorSafeContainer { } /// This protocol is an implementation detail of `ExtensibleCollectionType`; do /// not use it directly. /// /// Its requirements are inherited by `ExtensibleCollectionType` and thus must /// be satisfied by types conforming to that protocol. protocol _ExtensibleCollectionType : CollectionType { /// Create an empty instance init() /// A non-binding request to ensure `n` elements of available storage. /// /// This works as an optimization to avoid multiple reallocations of /// linear data structures like `Array`. Conforming types may /// reserve more than `n`, exactly `n`, less than `n` elements of /// storage, or even ignore the request completely. mutating func reserveCapacity(n: Self.Index.Distance) /// Append `x` to `self`. /// /// Applying `successor()` to the index of the new element yields /// `self.endIndex`. /// /// Complexity: amortized O(1). mutating func append(x: Self.Generator.Element) /// Append the elements of `newElements` to `self`. /// /// Complexity: O(*length of result*) /// /// A possible implementation:: /// /// reserveCapacity(count(self) + underestimateCount(newElements)) /// for x in newElements { /// self.append(x) /// } mutating func extend<S : SequenceType>(newElements: S) } /// This protocol is an implementation detail of `ForwardIndexType`; do /// not use it directly. /// /// Its requirements are inherited by `ForwardIndexType` and thus must /// be satisfied by types conforming to that protocol. protocol _ForwardIndexType : _Incrementable { /// A type that can represent the number of steps between pairs of /// `Self` values where one value is reachable from the other. /// /// Reachability is defined by the ability to produce one value from /// the other via zero or more applications of `successor`. typealias Distance : _SignedIntegerType = Int typealias _DisabledRangeIndex = _DisabledRangeIndex_ } /// This protocol is an implementation detail of `ForwardIndexType`; do /// not use it directly. /// /// Its requirements are inherited by `ForwardIndexType` and thus must /// be satisfied by types conforming to that protocol. protocol _Incrementable : Equatable { /// Return the next consecutive value in a discrete sequence of /// `Self` values /// /// Requires: `self` has a well-defined successor. func successor() -> Self } /// This protocol is an implementation detail of `IntegerArithmeticType`; do /// not use it directly. /// /// Its requirements are inherited by `IntegerArithmeticType` and thus must /// be satisfied by types conforming to that protocol. protocol _IntegerArithmeticType { /// Add `lhs` and `rhs`, returning a result and a `Bool` that is /// true iff the operation caused an arithmetic overflow. static func addWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool) /// Subtract `lhs` and `rhs`, returning a result and a `Bool` that is /// true iff the operation caused an arithmetic overflow. static func subtractWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool) /// Multiply `lhs` and `rhs`, returning a result and a `Bool` that is /// true iff the operation caused an arithmetic overflow. static func multiplyWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool) /// Divide `lhs` and `rhs`, returning a result and a `Bool` that is /// true iff the operation caused an arithmetic overflow. static func divideWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool) /// Divide `lhs` and `rhs`, returning the remainder and a `Bool` that is /// true iff the operation caused an arithmetic overflow. static func remainderWithOverflow(lhs: Self, _ rhs: Self) -> (Self, overflow: Bool) } /// This protocol is an implementation detail of `IntegerType`; do /// not use it directly. /// /// Its requirements are inherited by `IntegerType` and thus must /// be satisfied by types conforming to that protocol. protocol _IntegerType : IntegerLiteralConvertible, Printable, Hashable, IntegerArithmeticType, BitwiseOperationsType, _Incrementable { } /// A shadow for the "core operations" of NSArray. /// /// Covers a set of operations everyone needs to implement in order to /// be a useful `NSArray` subclass. @unsafe_no_objc_tagged_pointer @objc protocol _NSArrayCoreType : _NSCopyingType, _NSFastEnumerationType { func objectAtIndex(index: Int) -> AnyObject func getObjects(_: UnsafeMutablePointer<AnyObject>, range: _SwiftNSRange) func countByEnumeratingWithState(state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>, count: Int) -> Int var count: Int { get } } /// A shadow for the `NSCopying` protocol @objc protocol _NSCopyingType : _ShadowProtocol { func copyWithZone(zone: _SwiftNSZone) -> AnyObject } /// A shadow for the "core operations" of NSDictionary. /// /// Covers a set of operations everyone needs to implement in order to /// be a useful `NSDictionary` subclass. @objc protocol _NSDictionaryCoreType : _NSCopyingType, _NSFastEnumerationType { init(objects: UnsafePointer<AnyObject?>, forKeys: UnsafePointer<Void>, count: Int) var count: Int { get } func objectForKey(aKey: AnyObject?) -> AnyObject? func keyEnumerator() -> _NSEnumeratorType? func copyWithZone(zone: _SwiftNSZone) -> AnyObject func getObjects(objects: UnsafeMutablePointer<AnyObject>, andKeys keys: UnsafeMutablePointer<AnyObject>) func countByEnumeratingWithState(state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>, count: Int) -> Int } /// A shadow for the API of NSDictionary we will use in the core /// stdlib /// /// `NSDictionary` operations, in addition to those on /// `_NSDictionaryCoreType`, that we need to use from the core stdlib. /// Distinct from `_NSDictionaryCoreType` because we don't want to be /// forced to implement operations that `NSDictionary` already /// supplies. @unsafe_no_objc_tagged_pointer @objc protocol _NSDictionaryType : _NSDictionaryCoreType { func getObjects(objects: UnsafeMutablePointer<AnyObject>, andKeys keys: UnsafeMutablePointer<AnyObject>) } /// A shadow for the `NSEnumerator` class @objc protocol _NSEnumeratorType : _ShadowProtocol { init() func nextObject() -> AnyObject? } /// A shadow for the `NSFastEnumeration` protocol @objc protocol _NSFastEnumerationType : _ShadowProtocol { func countByEnumeratingWithState(state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>, count: Int) -> Int } /// A shadow for the "core operations" of NSSet. /// /// Covers a set of operations everyone needs to implement in order to /// be a useful `NSSet` subclass. @objc protocol _NSSetCoreType : _NSCopyingType, _NSFastEnumerationType { init(objects: UnsafePointer<AnyObject?>, count: Int) var count: Int { get } func member(member: AnyObject?) -> AnyObject? func objectEnumerator() -> _NSEnumeratorType? func copyWithZone(zone: _SwiftNSZone) -> AnyObject func countByEnumeratingWithState(state: UnsafeMutablePointer<_SwiftNSFastEnumerationState>, objects: UnsafeMutablePointer<AnyObject>, count: Int) -> Int } /// A shadow for the API of NSSet we will use in the core /// stdlib /// /// `NSSet` operations, in addition to those on /// `_NSSetCoreType`, that we need to use from the core stdlib. /// Distinct from `_NSSetCoreType` because we don't want to be /// forced to implement operations that `NSSet` already /// supplies. @unsafe_no_objc_tagged_pointer @objc protocol _NSSetType : _NSSetCoreType { } @objc protocol _NSStringCoreType : _NSCopyingType, _NSFastEnumerationType { func length() -> Int func characterAtIndex(index: Int) -> UInt16 } /// A Swift Array or Dictionary of types conforming to /// `_ObjectiveCBridgeable` can be passed to Objective-C as an NSArray or /// NSDictionary, respectively. The elements of the resulting NSArray /// or NSDictionary will be the result of calling `_bridgeToObjectiveC` /// on each elmeent of the source container. protocol _ObjectiveCBridgeable { typealias _ObjectiveCType /// Return true iff instances of `Self` can be converted to /// Objective-C. Even if this method returns `true`, A given /// instance of `Self._ObjectiveCType` may, or may not, convert /// successfully to `Self`; for example, an `NSArray` will only /// convert successfully to `[String]` if it contains only /// `NSString`\ s. static func _isBridgedToObjectiveC() -> Bool /// Must return `_ObjectiveCType.self`. static func _getObjectiveCType() -> Any.Type /// Convert `self` to Objective-C func _bridgeToObjectiveC() -> _ObjectiveCType /// Bridge from an Objective-C object of the bridged class type to a /// value of the Self type. /// /// This bridging operation is used for forced downcasting (e.g., /// via as), and may defer complete checking until later. For /// example, when bridging from NSArray to Array<T>, we can defer /// the checking for the individual elements of the array. /// /// :param: result The location where the result is written. The optional /// will always contain a value. static func _forceBridgeFromObjectiveC(source: _ObjectiveCType, inout result: Self?) /// Try to bridge from an Objective-C object of the bridged class /// type to a value of the Self type. /// /// This conditional bridging operation is used for conditional /// downcasting (e.g., via as?) and therefore must perform a /// complete conversion to the value type; it cannot defer checking /// to a later time. /// /// :param: result The location where the result is written. /// /// :returns: true if bridging succeeded, false otherwise. This redundant /// information is provided for the convenience of the runtime's dynamic_cast /// implementation, so that it need not look into the optional representation /// to determine success. static func _conditionallyBridgeFromObjectiveC(source: _ObjectiveCType, inout result: Self?) -> Bool } /// A stdlib-internal protocol modeled by the intrinsic pointer types, /// UnsafeMutablePointer, UnsafePointer, and /// AutoreleasingUnsafeMutablePointer. protocol _PointerType { /// The underlying raw pointer value. var _rawValue: Builtin.RawPointer { get } /// Construct a pointer from a raw value. init(_ _rawValue: Builtin.RawPointer) } /// This protocol is an implementation detail of `RandomAccessIndexType`; do /// not use it directly. /// /// Its requirements are inherited by `RandomAccessIndexType` and thus must /// be satisfied by types conforming to that protocol. protocol _RandomAccessIndexType : _BidirectionalIndexType, Strideable { /// Return the minimum number of applications of `successor` or /// `predecessor` required to reach `other` from `self`. /// /// Complexity: O(1). /// /// Axioms:: /// /// x.distanceTo(x.successor())) == 1 /// x.distanceTo(x.predecessor())) == -1 /// x.advancedBy(x.distanceTo(y)) == y func distanceTo(other: Self) -> Self.Distance /// Return `self` offset by `n` steps. /// /// :returns: If `n > 0`, the result of applying `successor` to /// `self` `n` times. If `n < 0`, the result of applying /// `predecessor` to `self` `-n` times. Otherwise, `self`. /// /// Complexity: O(1) /// /// Axioms:: /// /// x.advancedBy(0) == x /// x.advancedBy(1) == x.successor() /// x.advancedBy(-1) == x.predecessor() /// x.distanceTo(x.advancedBy(m)) == m func advancedBy(n: Self.Distance) -> Self } /// This protocol is an implementation detail of `RawOptionSetType`; do /// not use it directly. /// /// Its requirements are inherited by `RawOptionSetType` and thus must /// be satisfied by types conforming to that protocol. protocol _RawOptionSetType : RawRepresentable, Equatable { typealias RawValue : BitwiseOperationsType, Equatable init(rawValue: RawValue) } /// This protocol is an implementation detail of `SequenceType`; do /// not use it directly. /// /// Its requirements are inherited by `SequenceType` and thus must /// be satisfied by types conforming to that protocol. protocol _SequenceType { } /// This protocol is an implementation detail of `SequenceType`; do /// not use it directly. /// /// Its requirements are inherited by `SequenceType` and thus must /// be satisfied by types conforming to that protocol. protocol _Sequence_Type : _SequenceType { /// A type whose instances can produce the elements of this /// sequence, in order. typealias Generator : GeneratorType /// Return a *generator* over the elements of this *sequence*. The /// *generator*\ 's next element is the first element of the /// sequence. /// /// Complexity: O(1) func generate() -> Generator } @objc protocol _ShadowProtocol { } /// This protocol is an implementation detail of `SignedIntegerType`; /// do not use it directly. /// /// Its requirements are inherited by `SignedIntegerType` and thus /// must be satisfied by types conforming to that protocol. protocol _SignedIntegerType : _IntegerType, SignedNumberType { /// Represent this number using Swift's widest native signed integer /// type. func toIntMax() -> IntMax /// Convert from Swift's widest signed integer type, trapping on /// overflow. init(_: IntMax) } /// This protocol is an implementation detail of `SignedNumberType`; do /// not use it directly. /// /// Its requirements are inherited by `SignedNumberType` and thus must /// be satisfied by types conforming to that protocol. protocol _SignedNumberType : Comparable, IntegerLiteralConvertible { /// Return the difference between `lhs` and `rhs`. func -(lhs: Self, rhs: Self) -> Self } /// This protocol is an implementation detail of `Sliceable`; do /// not use it directly. /// /// Its requirements are inherited by `Sliceable` and thus must /// be satisfied by types conforming to that protocol. protocol _Sliceable : CollectionType { } /// This protocol is an implementation detail of `Strideable`; do /// not use it directly. /// /// Its requirements are inherited by `Strideable` and thus must /// be satisfied by types conforming to that protocol. protocol _Strideable { /// A type that can represent the distance between two values of `Self` typealias Stride : SignedNumberType /// Returns a stride `x` such that `self.advancedBy(x)` approximates /// `other`. /// /// Complexity: O(1). /// /// See also: `RandomAccessIndexType`\ 's `distanceTo`, which provides a /// stronger semantic guarantee. func distanceTo(other: Self) -> Stride /// Returns a `Self` `x` such that `self.distanceTo(x)` approximates /// `n`. /// /// Complexity: O(1). /// /// See also: `RandomAccessIndexType`\ 's `advancedBy`, which /// provides a stronger semantic guarantee. func advancedBy(n: Stride) -> Self } /// Instances of conforming types are used in internal `String` /// representation. protocol _StringElementType { static func _toUTF16CodeUnit(_: Self) -> CodeUnit static func _fromUTF16CodeUnit(utf16: CodeUnit) -> Self } /// This protocol is an implementation detail of `SignedIntegerType`; /// do not use it directly. /// /// Its requirements are inherited by `SignedIntegerType` and thus /// must be satisfied by types conforming to that protocol. protocol _UnsignedIntegerType : _IntegerType { typealias _DisallowMixedSignArithmetic : SignedIntegerType = Int /// Represent this number using Swift's widest native unsigned /// integer type. func toUIntMax() -> UIntMax /// Convert from Swift's widest unsigned integer type, trapping on /// overflow. init(_: UIntMax) } protocol __ArrayType : _CollectionType { var count: Int { get } typealias _Buffer : _ArrayBufferType var _buffer: _Buffer { get } func _doCopyToNativeArrayBuffer() -> _ContiguousArrayBuffer<Self._Element> } /// Return the absolute value of `x`. /// /// Concrete instances of `SignedNumberType` can specialize this /// function by conforming to `AbsoluteValuable`. func abs<T : SignedNumberType>(x: T) -> T /// Return the result of advancing start by `n` positions, or until it /// equals `end`. If `T` models `RandomAccessIndexType`, executes in /// O(1). Otherwise, executes in O(`abs(n)`). If `T` does not model /// `BidirectionalIndexType`, requires that `n` is non-negative. func advance<T : ForwardIndexType>(start: T, n: T.Distance, end: T) -> T /// Return the result of advancing `start` by `n` positions. If `T` /// models `RandomAccessIndexType`, executes in O(1). Otherwise, /// executes in O(`abs(n)`). If `T` does not model /// `BidirectionalIndexType`, requires that `n` is non-negative. func advance<T : ForwardIndexType>(start: T, n: T.Distance) -> T /// Returns the minimum memory alignment of `T`. func alignof<T>(_: T.Type) -> Int /// Returns the minimum memory alignment of `T`. func alignofValue<T>(_: T) -> Int /// Traditional C-style assert with an optional message. /// /// Use this function for internal sanity checks that are active /// during testing but do not impact performance of shipping code. /// To check for invalid usage in Release builds; see `precondition`. /// /// * In playgrounds and -Onone builds (the default for Xcode's Debug /// configuration): if `condition` evaluates to false, stop program /// execution in a debuggable state after printing `message`. /// /// * In -O builds (the default for Xcode's Release configuration), /// `condition` is not evaluated, and there are no effects. /// /// * In -Ounchecked builds, `condition` is not evaluated, but the /// optimizer may assume that it *would* evaluate to `true`. Failure /// to satisfy that assumption in -Ounchecked builds is a serious /// programming error. func assert(condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String = "", file: StaticString = "", line: UWord = "") /// Indicate that an internal sanity check failed. /// /// Use this function to stop the program, without impacting the /// performance of shipping code, when control flow is not expected to /// reach the call (e.g. in the `default` case of a `switch` where you /// have knowledge that one of the other cases must be satisfied). To /// protect code from invalid usage in Release builds; see /// `preconditionFailure`. /// /// * In playgrounds and -Onone builds (the default for Xcode's Debug /// configuration) stop program execution in a debuggable state /// after printing `message`. /// /// * In -O builds, has no effect. /// /// * In -Ounchecked builds, the optimizer may assume that this /// function will never be called. Failure to satisfy that assumption /// is a serious programming error. @inline(__always) func assertionFailure(_ message: @autoclosure () -> String = "", file: StaticString = "", line: UWord = "") /// Return `true` iff an element in `seq` satisfies `predicate`. func contains<S : SequenceType, L : BooleanType>(seq: S, predicate: @noescape (S.Generator.Element) -> L) -> Bool /// Return `true` iff `x` is in `seq`. func contains<S : SequenceType where S.Generator.Element : Equatable>(seq: S, x: S.Generator.Element) -> Bool /// Return the number of elements in x. /// /// O(1) if T.Index is RandomAccessIndexType; O(N) otherwise. func count<T : _CollectionType>(x: T) -> T.Index.Distance /// Write to `target` the textual representation of `x` most suitable /// for debugging. /// /// * If `T` conforms to `DebugPrintable`, write `x.debugDescription` /// * Otherwise, if `T` conforms to `Printable`, write `x.description` /// * Otherwise, if `T` conforms to `Streamable`, write `x` /// * Otherwise, fall back to a default textual representation. /// /// See also: `debugPrintln(x, &target)` @inline(never) func debugPrint<T, TargetStream : OutputStreamType>(value: T, inout target: TargetStream) /// Write to the console the textual representation of `x` most suitable /// for debugging. /// /// * If `T` conforms to `DebugPrintable`, write `x.debugDescription` /// * Otherwise, if `T` conforms to `Printable`, write `x.description` /// * Otherwise, if `T` conforms to `Streamable`, write `x` /// * Otherwise, fall back to a default textual representation. /// /// See also: `debugPrintln(x)` @inline(never) func debugPrint<T>(x: T) /// Write to the console the textual representation of `x` most suitable /// for debugging, followed by a newline. /// /// * If `T` conforms to `DebugPrintable`, write `x.debugDescription` /// * Otherwise, if `T` conforms to `Printable`, write `x.description` /// * Otherwise, if `T` conforms to `Streamable`, write `x` /// * Otherwise, fall back to a default textual representation. /// /// See also: `debugPrint(x)` @inline(never) func debugPrintln<T>(x: T) /// Write to `target` the textual representation of `x` most suitable /// for debugging, followed by a newline. /// /// * If `T` conforms to `DebugPrintable`, write `x.debugDescription` /// * Otherwise, if `T` conforms to `Printable`, write `x.description` /// * Otherwise, if `T` conforms to `Streamable`, write `x` /// * Otherwise, fall back to a default textual representation. /// /// See also: `debugPrint(x, &target)` @inline(never) func debugPrintln<T, TargetStream : OutputStreamType>(x: T, inout target: TargetStream) /// Measure the distance between `start` and `end`. /// /// If `T` models `RandomAccessIndexType`, requires that `start` and `end` are /// part of the same sequence, and executes in O(1). /// /// Otherwise, requires that `end` is reachable from `start` by /// incrementation, and executes in O(N), where N is the function's /// result. func distance<T : ForwardIndexType>(start: T, end: T) -> T.Distance /// Return a slice containing all but the first element of `s`. /// /// Requires: `s` is non-empty. func dropFirst<Seq : Sliceable>(s: Seq) -> Seq.SubSlice /// Return a slice containing all but the last element of `s`. /// /// Requires: `s` is non-empty. func dropLast<S : Sliceable where S.Index : BidirectionalIndexType>(s: S) -> S.SubSlice /// Dump an object's contents using its mirror to the specified output stream. func dump<T, TargetStream : OutputStreamType>(x: T, inout targetStream: TargetStream, name: String? = default, indent: Int = default, maxDepth: Int = default, maxItems: Int = default) -> T /// Dump an object's contents using its mirror to standard output. func dump<T>(x: T, name: String? = default, indent: Int = default, maxDepth: Int = default, maxItems: Int = default) -> T /// Return a lazy `SequenceType` containing pairs (*n*, *x*), where /// *n*\ s are consecutive `Int`\ s starting at zero, and *x*\ s are /// the elements of `base`:: /// /// > for (n, c) in enumerate("Swift") { println("\(n): '\(c)'" )} /// 0: 'S' /// 1: 'w' /// 2: 'i' /// 3: 'f' /// 4: 't' func enumerate<Seq : SequenceType>(base: Seq) -> EnumerateSequence<Seq> /// Return `true` iff `a1` and `a2` contain the same elements in the /// same order. func equal<S1 : SequenceType, S2 : SequenceType where S1.Generator.Element == S1.Generator.Element, S1.Generator.Element : Equatable>(a1: S1, a2: S2) -> Bool /// Return true iff `a1` and `a2` contain equivalent elements, using /// `isEquivalent` as the equivalence test. Requires: `isEquivalent` /// is an `equivalence relation /// <http://en.wikipedia.org/wiki/Equivalence_relation>`_ func equal<S1 : SequenceType, S2 : SequenceType where S1.Generator.Element == S1.Generator.Element>(a1: S1, a2: S2, isEquivalent: @noescape (S1.Generator.Element, S1.Generator.Element) -> Bool) -> Bool /// Append elements from `newElements` to `x`. Complexity: /// O(N) func extend<C : RangeReplaceableCollectionType, S : CollectionType where C.Generator.Element == C.Generator.Element>(inout x: C, newElements: S) /// Unconditionally print a `message` and stop execution. @noreturn func fatalError(_ message: @autoclosure () -> String = default, file: StaticString = default, line: UWord = default) /// Return an `Array` containing the elements of `source`, /// in order, that satisfy the predicate `includeElement`. func filter<S : SequenceType>(source: S, includeElement: (S.Generator.Element) -> Bool) -> [S.Generator.Element] /// Returns the first index where `value` appears in `domain` or `nil` if /// `value` is not found. /// /// Complexity: O(\ `count(domain)`\ ) func find<C : CollectionType where C.Generator.Element : Equatable>(domain: C, value: C.Generator.Element) -> C.Index? /// Returns the first element of `x`, or `nil` if `x` is empty. func first<C : CollectionType>(x: C) -> C.Generator.Element? /// Return an `Array` containing the results of mapping `transform` /// over `source` and flattening the result. func flatMap<S : SequenceType, T>(source: S, transform: @noescape (S.Generator.Element) -> [T]) -> [T] /// Return an `Array` containing the results of mapping `transform` /// over `source` and flattening the result. func flatMap<C : CollectionType, T>(source: C, transform: (C.Generator.Element) -> [T]) -> [T] /// Returns `f(self)!` iff `self` and `f(self)` are not nil. func flatMap<T, U>(x: T?, f: @noescape (T) -> U?) -> U? /// Returns a `CVaListPointer` built from `args` that's backed by /// autoreleased storage. /// /// .. Warning:: This function is best avoided in favor of /// `withVaList`, but occasionally (i.e. in a `class` initializer) you /// may find that the language rules don't allow you to use /// `withVaList` as intended. func getVaList(args: [CVarArgType]) -> CVaListPointer /// Return the range of `x` 's valid index values. /// /// The result's `endIndex` is the same as that of `x`. Because /// `Range` is half-open, iterating the values of the result produces /// all valid subscript arguments for `x`, omitting its `endIndex`. func indices<C : CollectionType>(x: C) -> Range<C.Index> /// Insert `newElement` into `x` at index `i`. /// /// Invalidates all indices with respect to `x`. /// /// Complexity: O(\ `count(x)`\ ). func insert<C : RangeReplaceableCollectionType>(inout x: C, newElement: C.Generator.Element, atIndex i: C.Index) /// Returns `true` iff `x` is empty. func isEmpty<C : CollectionType>(x: C) -> Bool /// Returns `true` iff `object` is a non-\ `@objc` class instance with a single /// strong reference. /// /// * Does *not* modify `object`; the use of `inout` is an /// implementation artifact. /// * Weak references do not affect the result of this function. /// /// Useful for implementing the copy-on-write optimization for the /// deep storage of value types:: /// /// mutating func modifyMe(arg: X) { /// if isUniquelyReferenced(&myStorage) { /// myStorage.modifyInPlace(arg) /// } /// else { /// myStorage = myStorage.createModified(arg) /// } /// } /// /// This function is safe to use for `mutating` functions in /// multithreaded code because a false positive would imply that there /// is already a user-level data race on the value being mutated. func isUniquelyReferenced<T : NonObjectiveCBase>(inout object: T) -> Bool /// Returns `true` iff `object` is a non-\ `@objc` class instance with /// a single strong reference. /// /// * Does *not* modify `object`; the use of `inout` is an /// implementation artifact. /// * If `object` is an Objective-C class instance, returns `false`. /// * Weak references do not affect the result of this function. /// /// Useful for implementing the copy-on-write optimization for the /// deep storage of value types:: /// /// mutating func modifyMe(arg: X) { /// if isUniquelyReferencedNonObjC(&myStorage) { /// myStorage.modifyInPlace(arg) /// } /// else { /// myStorage = self.createModified(myStorage, arg) /// } /// } /// /// This function is safe to use for `mutating` functions in /// multithreaded code because a false positive would imply that there /// is already a user-level data race on the value being mutated. func isUniquelyReferencedNonObjC<T>(inout object: T) -> Bool /// Returns `true` iff `object` is a non-\ `@objc` class instance with /// a single strong reference. /// /// * Does *not* modify `object`; the use of `inout` is an /// implementation artifact. /// * If `object` is an Objective-C class instance, returns `false`. /// * Weak references do not affect the result of this function. /// /// Useful for implementing the copy-on-write optimization for the /// deep storage of value types:: /// /// mutating func modifyMe(arg: X) { /// if isUniquelyReferencedNonObjC(&myStorage) { /// myStorage.modifyInPlace(arg) /// } /// else { /// myStorage = self.createModified(myStorage, arg) /// } /// } /// /// This function is safe to use for `mutating` functions in /// multithreaded code because a false positive would imply that there /// is already a user-level data race on the value being mutated. func isUniquelyReferencedNonObjC<T>(inout object: T?) -> Bool /// Creates and returns a collection of type `C` that is the result of /// interposing a given separator between the elements of the sequence /// `elements`. /// /// For example, this code excerpt writes "``here be dragons``" to the standard /// output:: /// /// println(join(" ", [ "here", "be", "dragons" ])) func join<C : ExtensibleCollectionType, S : SequenceType where C == C>(separator: C, elements: S) -> C /// Returns the last element of `x`, or `nil` if `x` is empty. func last<C : CollectionType where C.Index : BidirectionalIndexType>(x: C) -> C.Generator.Element? /// Augment `s` with lazy methods such as `map`, `filter`, etc. func lazy<S : CollectionType where S.Index : RandomAccessIndexType>(s: S) -> LazyRandomAccessCollection<S> /// Augment `s` with lazy methods such as `map`, `filter`, etc. func lazy<S : SequenceType>(s: S) -> LazySequence<S> /// Augment `s` with lazy methods such as `map`, `filter`, etc. func lazy<S : CollectionType where S.Index : ForwardIndexType>(s: S) -> LazyForwardCollection<S> /// Augment `s` with lazy methods such as `map`, `filter`, etc. func lazy<S : CollectionType where S.Index : BidirectionalIndexType>(s: S) -> LazyBidirectionalCollection<S> /// Return true iff `a1` precedes `a2` in a lexicographical ("dictionary") /// ordering, using `isOrderedBefore` as the comparison between elements. /// /// Requires: isOrderedBefore` is a `strict weak ordering /// <http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings>`__ /// over the elements of `a1` and `a2`. func lexicographicalCompare<S1 : SequenceType, S2 : SequenceType where S1.Generator.Element == S1.Generator.Element>(a1: S1, a2: S2, isOrderedBefore less: @noescape (S1.Generator.Element, S1.Generator.Element) -> Bool) -> Bool /// Return true iff a1 precedes a2 in a lexicographical ("dictionary") /// ordering, using "<" as the comparison between elements. func lexicographicalCompare<S1 : SequenceType, S2 : SequenceType where S1.Generator.Element == S1.Generator.Element, S1.Generator.Element : Comparable>(a1: S1, a2: S2) -> Bool /// Return an `Array` containing the results of mapping `transform` /// over `source`. func map<C : CollectionType, T>(source: C, transform: (C.Generator.Element) -> T) -> [T] /// Return an `Array` containing the results of mapping `transform` /// over `source`. func map<S : SequenceType, T>(source: S, transform: (S.Generator.Element) -> T) -> [T] /// Haskell's fmap for Optionals. func map<T, U>(x: T?, f: @noescape (T) -> U) -> U? /// Return the greater of `x` and `y` func max<T : Comparable>(x: T, y: T) -> T /// Return the greatest argument passed func max<T : Comparable>(x: T, y: T, z: T, rest: T...) -> T /// Returns the maximum element in `elements`. Requires: /// `elements` is non-empty. O(count(elements)) func maxElement<R : SequenceType where R.Generator.Element : Comparable>(elements: R) -> R.Generator.Element /// Return the least argument passed func min<T : Comparable>(x: T, y: T, z: T, rest: T...) -> T /// Return the lesser of `x` and `y` func min<T : Comparable>(x: T, y: T) -> T /// Returns the minimum element in `elements`. Requires: /// `elements` is non-empty. O(count(elements)) func minElement<R : SequenceType where R.Generator.Element : Comparable>(elements: R) -> R.Generator.Element /// Convert `x` to type `U`, trapping on overflow in -Onone and -O /// builds. /// /// Typically used to do conversion to any contextually-deduced /// integer type:: /// /// func f(x: Int32) {} /// func g(x: UInt64) { f(numericCast(x)) } func numericCast<T : _UnsignedIntegerType, U : _SignedIntegerType>(x: T) -> U /// Convert `x` to type `U`, trapping on overflow in -Onone and -O /// builds. /// /// Typically used to do conversion to any contextually-deduced /// integer type:: /// /// func f(x: UInt32) {} /// func g(x: Int64) { f(numericCast(x)) } func numericCast<T : _SignedIntegerType, U : _UnsignedIntegerType>(x: T) -> U /// Convert `x` to type `U`, trapping on overflow in -Onone and -O /// builds. /// /// Typically used to do conversion to any contextually-deduced /// integer type:: /// /// func f(x: UInt32) {} /// func g(x: UInt64) { f(numericCast(x)) } func numericCast<T : _UnsignedIntegerType, U : _UnsignedIntegerType>(x: T) -> U /// Convert `x` to type `U`, trapping on overflow in -Onone and -O /// builds. /// /// Typically used to do conversion to any contextually-deduced /// integer type:: /// /// func f(x: Int32) {} /// func g(x: Int64) { f(numericCast(x)) } func numericCast<T : _SignedIntegerType, U : _SignedIntegerType>(x: T) -> U /// Returns `true` if `lhs` and `rhs` have a non-empty intersection func overlaps<I0 : IntervalType, I1 : IntervalType where I0.Bound == I0.Bound>(lhs: I0, rhs: I1) -> Bool /// Re-order the given `range` of `elements` and return a pivot index /// *p*. /// /// Postcondition: for all *i* in `range.startIndex..<`\ *p*, and *j* /// in *p*\ `..<range.endIndex`, `less(elements[`\ *i*\ `], /// elements[`\ *j*\ `]) && !less(elements[`\ *j*\ `], /// elements[`\ *p*\ `])`. Only returns `range.endIndex` when /// `elements` is empty. /// Requires: `isOrderedBefore` is a `strict weak ordering /// <http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings>`__ /// over `elements`. func partition<C : MutableCollectionType where C.Index : RandomAccessIndexType>(inout elements: C, range: Range<C.Index>, isOrderedBefore: (C.Generator.Element, C.Generator.Element) -> Bool) -> C.Index /// Re-order the given `range` of `elements` and return a pivot index /// *p*. /// /// Postcondition: for all *i* in `range.startIndex..<`\ *p*, and *j* /// in *p*\ `..<range.endIndex`, `less(elements[`\ *i*\ `], /// elements[`\ *j*\ `]) && !less(elements[`\ *j*\ `], /// elements[`\ *p*\ `])`. Only returns `range.endIndex` when /// `elements` is empty. /// Requires: The less-than operator (`func <`) defined in the `Comparable` /// conformance is a `strict weak ordering /// <http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings>`__ /// over `elements`. func partition<C : MutableCollectionType where C.Index : RandomAccessIndexType, C.Generator.Element : Comparable>(inout elements: C, range: Range<C.Index>) -> C.Index /// Check a necessary condition for making forward progress. /// /// Use this function to detect conditions that must prevent the /// program from proceeding even in shipping code. /// /// * In playgrounds and -Onone builds (the default for Xcode's Debug /// configuration): if `condition` evaluates to false, stop program /// execution in a debuggable state after printing `message`. /// /// * In -O builds (the default for Xcode's Release configuration): /// if `condition` evaluates to false, stop program execution. /// /// * In -Ounchecked builds, `condition` is not evaluated, but the /// optimizer may assume that it *would* evaluate to `true`. Failure /// to satisfy that assumption in -Ounchecked builds is a serious /// programming error. func precondition(condition: @autoclosure () -> Bool, _ message: @autoclosure () -> String = default, file: StaticString = default, line: UWord = default) /// Indicate that a precondition was violated. /// /// Use this function to stop the program when control flow can only /// reach the call if your API was improperly used. /// /// * In playgrounds and -Onone builds (the default for Xcode's Debug /// configuration), stop program execution in a debuggable state /// after printing `message`. /// /// * In -O builds (the default for Xcode's Release configuration), /// stop program execution. /// /// * In -Ounchecked builds, the optimizer may assume that this /// function will never be called. Failure to satisfy that assumption /// is a serious programming error. @noreturn func preconditionFailure(_ message: @autoclosure () -> String = default, file: StaticString = default, line: UWord = default) /// Return a slice, up to `maxLength` in length, containing the /// initial elements of `s`. /// /// If `maxLength` exceeds `count(s)`, the result contains all /// the elements of `s`. /// /// Complexity: O(1)+K when `S.Index` conforms to /// `RandomAccessIndexType` and O(N)+K otherwise, where K is the cost /// of slicing `s`. func prefix<S : Sliceable>(s: S, maxLength: Int) -> S.SubSlice /// Writes the textual representation of `value` into the stream `target`. /// /// The textual representation is obtained from the `value` using its protocol /// conformances, in the following order of preference: `Streamable`, /// `Printable`, `DebugPrintable`. /// /// Do not overload this function for your type. Instead, adopt one of the /// protocols mentioned above. @inline(never) func print<T, TargetStream : OutputStreamType>(value: T, inout target: TargetStream) /// Writes the textual representation of `value` into the standard output. /// /// The textual representation is obtained from the `value` using its protocol /// conformances, in the following order of preference: `Streamable`, /// `Printable`, `DebugPrintable`. /// /// Do not overload this function for your type. Instead, adopt one of the /// protocols mentioned above. @inline(never) func print<T>(value: T) /// Writes the textual representation of `value` and a newline character into /// the stream `target`. /// /// The textual representation is obtained from the `value` using its protocol /// conformances, in the following order of preference: `Streamable`, /// `Printable`, `DebugPrintable`. /// /// Do not overload this function for your type. Instead, adopt one of the /// protocols mentioned above. @inline(never) func println<T, TargetStream : OutputStreamType>(value: T, inout target: TargetStream) /// Writes the textual representation of `value` and a newline character into /// the standard output. /// /// The textual representation is obtained from the `value` using its protocol /// conformances, in the following order of preference: `Streamable`, /// `Printable`, `DebugPrintable`. /// /// Do not overload this function for your type. Instead, adopt one of the /// protocols mentioned above. @inline(never) func println<T>(value: T) /// Writes a single newline character into the standard output. @inline(never) func println() /// Return the result of repeatedly calling `combine` with an /// accumulated value initialized to `initial` and each element of /// `sequence`, in turn. func reduce<S : SequenceType, U>(sequence: S, initial: U, combine: @noescape (U, S.Generator.Element) -> U) -> U /// Produce a mirror for any value. If the value's type conforms to Reflectable, /// invoke its getMirror() method; otherwise, fall back to an implementation /// in the runtime that structurally reflects values of any type. func reflect<T>(x: T) -> MirrorType /// Remove all elements from `x` /// /// Invalidates all indices with respect to `x`. /// /// :param: `keepCapacity`, if `true`, is a non-binding request to /// avoid releasing storage, which can be a useful optimization /// when `x` is going to be grown again. /// /// Complexity: O(\ `count(x)`\ ). func removeAll<C : RangeReplaceableCollectionType>(inout x: C, keepCapacity: Bool) /// Remove from `x` and return the element at index `i` /// /// Invalidates all indices with respect to `x`. /// /// Complexity: O(\ `count(x)`\ ). func removeAtIndex<C : RangeReplaceableCollectionType>(inout x: C, index: C.Index) -> C.Generator.Element /// Remove an element from the end of `x` in O(1). /// Requires: `x` is nonempty func removeLast<C : RangeReplaceableCollectionType where C.Index : BidirectionalIndexType>(inout x: C) -> C.Generator.Element /// Remove from `x` the indicated `subRange` of elements /// /// Invalidates all indices with respect to `x`. /// /// Complexity: O(\ `count(x)`\ ). func removeRange<C : RangeReplaceableCollectionType>(inout x: C, subRange: Range<C.Index>) /// Return an `Array` containing the elements of `source` in reverse /// order. func reverse<C : CollectionType where C.Index : BidirectionalIndexType>(source: C) -> [C.Generator.Element] /// Returns the contiguous memory footprint of `T`. /// /// Does not include any dynamically-allocated or "remote" storage. /// In particular, `sizeof(X.self)`, when `X` is a class type, is the /// same regardless of how many stored properties `X` has. func sizeof<T>(_: T.Type) -> Int /// Returns the contiguous memory footprint of `T`. /// /// Does not include any dynamically-allocated or "remote" storage. /// In particular, `sizeof(a)`, when `a` is a class instance, is the /// same regardless of how many stored properties `a` has. func sizeofValue<T>(_: T) -> Int func sort<T>(inout array: ContiguousArray<T>, isOrderedBefore: (T, T) -> Bool) /// Sort `collection` in-place. /// /// The sorting algorithm is not stable (can change the relative order of /// elements that compare equal). /// /// Requires: The less-than operator (`func <`) defined in the `Comparable` /// conformance is a `strict weak ordering /// <http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings>`__ /// over `elements`. func sort<C : MutableCollectionType where C.Index : RandomAccessIndexType, C.Generator.Element : Comparable>(inout collection: C) func sort<T : Comparable>(inout array: [T]) func sort<T : Comparable>(inout array: ContiguousArray<T>) /// Sort `collection` in-place according to `isOrderedBefore`. /// /// The sorting algorithm is not stable (can change the relative order of /// elements for which `isOrderedBefore` does not establish an order). /// /// Requires: `isOrderedBefore` is a `strict weak ordering /// <http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings>`__ /// over `elements`. func sort<C : MutableCollectionType where C.Index : RandomAccessIndexType>(inout collection: C, isOrderedBefore: (C.Generator.Element, C.Generator.Element) -> Bool) func sort<T>(inout array: [T], isOrderedBefore: (T, T) -> Bool) /// Return an `Array` containing the sorted elements of `source`{according}. /// /// The sorting algorithm is not stable (can change the relative order of /// elements for which `isOrderedBefore` does not establish an order). /// /// Requires: `isOrderedBefore` is a `strict weak ordering /// <http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings>`__ /// over `elements`. func sorted<C : SequenceType>(source: C, isOrderedBefore: (C.Generator.Element, C.Generator.Element) -> Bool) -> [C.Generator.Element] /// Return an `Array` containing the sorted elements of `source`{according}. /// /// The sorting algorithm is not stable (can change the relative order of /// elements that compare equal). /// /// Requires: The less-than operator (`func <`) defined in the `Comparable` /// conformance is a `strict weak ordering /// <http://en.wikipedia.org/wiki/Strict_weak_order#Strict_weak_orderings>`__ /// over `elements`. func sorted<C : SequenceType where C.Generator.Element : Comparable>(source: C) -> [C.Generator.Element] /// Insert `newElements` into `x` at index `i` /// /// Invalidates all indices with respect to `x`. /// /// Complexity: O(\ `count(x) + count(newElements)`\ ). func splice<C : RangeReplaceableCollectionType, S : CollectionType where C.Generator.Element == C.Generator.Element>(inout x: C, newElements: S, atIndex i: C.Index) /// Return the result of slicing `elements` into sub-sequences that /// don't contain elements satisfying the predicate `isSeparator`. /// /// :param: maxSplit the maximum number of slices to return, minus 1. /// If `maxSplit + 1` slices would otherwise be returned, the /// algorithm stops splitting and returns a suffix of `elements` /// /// :param: allowEmptySlices if true, an empty slice is produced in /// the result for each pair of consecutive func split<S : Sliceable, R : BooleanType>(elements: S, maxSplit: Int, allowEmptySlices: Bool, #isSeparator: @noescape (S.Generator.Element) -> R) -> [S.SubSlice] /// Return true iff the the initial elements of `s` are equal to `prefix`. func startsWith<S0 : SequenceType, S1 : SequenceType where S0.Generator.Element == S0.Generator.Element, S0.Generator.Element : Equatable>(s: S0, prefix: S1) -> Bool /// Return true iff `s` begins with elements equivalent to those of /// `prefix`, using `isEquivalent` as the equivalence test. /// /// Requires: `isEquivalent` is an `equivalence relation /// <http://en.wikipedia.org/wiki/Equivalence_relation>`_ func startsWith<S0 : SequenceType, S1 : SequenceType where S0.Generator.Element == S0.Generator.Element>(s: S0, prefix: S1, isEquivalent: @noescape (S0.Generator.Element, S0.Generator.Element) -> Bool) -> Bool /// Return the sequence of values (`start`, `start + stride`, `start + /// stride + stride`, ... *last*) where *last* is the last value in /// the progression less than or equal to `end`. /// /// .. Note:: There is no guarantee that `end` is an element of the /// sequence. func stride<T : Strideable>(from start: T, through end: T, by stride: T.Stride) -> StrideThrough<T> /// Return the sequence of values (`start`, `start + stride`, `start + /// stride + stride`, ... *last*) where *last* is the last value in /// the progression that is less than `end`. func stride<T : Strideable>(from start: T, to end: T, by stride: T.Stride) -> StrideTo<T> /// Returns the least possible interval between distinct instances of /// `T` in memory. The result is always positive. func strideof<T>(_: T.Type) -> Int /// Returns the least possible interval between distinct instances of /// `T` in memory. The result is always positive. func strideofValue<T>(_: T) -> Int /// Return a slice, up to `maxLength` in length, containing the /// final elements of `s`. /// /// If `maxLength` exceeds `count(s)`, the result contains all /// the elements of `s`. /// /// Complexity: O(1)+K when `S.Index` conforms to /// `RandomAccessIndexType` and O(N)+K otherwise, where K is the cost /// of slicing `s`. func suffix<S : Sliceable where S.Index : BidirectionalIndexType>(s: S, maxLength: Int) -> S.SubSlice /// Exchange the values of `a` and `b` func swap<T>(inout a: T, inout b: T) /// Returns the result of `debugPrint`\ 'ing `x` into a `String` func toDebugString<T>(x: T) -> String /// Returns the result of `print`\ 'ing `x` into a `String` @inline(never) func toString<T>(x: T) -> String /// Translate `input`, in the given `InputEncoding`, into `output`, in /// the given `OutputEncoding`. /// /// :param: `stopOnError` causes encoding to stop when an encoding /// error is detected in `input`, if `true`. Otherwise, U+FFFD /// replacement characters are inserted for each detected error. func transcode<Input : GeneratorType, Output : SinkType, InputEncoding : UnicodeCodecType, OutputEncoding : UnicodeCodecType where Input.Element == Input.Element, Output.Element == Output.Element>(inputEncoding: InputEncoding.Type, outputEncoding: OutputEncoding.Type, input: Input, inout output: Output, #stopOnError: Bool) -> Bool /// Return an underestimate of the number of elements in the given /// sequence, without consuming the sequence. For Sequences that are /// actually Collections, this will return count(x) func underestimateCount<T : SequenceType>(x: T) -> Int /// Return an UnsafePointer to the storage used for `object`. There's /// not much you can do with this other than use it to identify the /// object func unsafeAddressOf(object: AnyObject) -> UnsafePointer<Void> /// Returns the the bits of `x`, interpreted as having type `U`. /// /// .. Caution:: Breaks the guarantees of Swift's type system; use /// with extreme care. There's almost always a better way to do /// anything. /// func unsafeBitCast<T, U>(x: T, _: U.Type) -> U /// Returns: `x as T` /// /// Requires: `x is T`. In particular, in -O builds, no test is /// performed to ensure that `x` actually has dynamic type `T`. /// /// .. Danger:: trades safety for performance. Use `unsafeDowncast` /// only when `x as T` has proven to be a performance problem and you /// are confident that, always, `x is T`. It is better than an /// `unsafeBitCast` because it's more restrictive, and because /// checking is still performed in debug builds. func unsafeDowncast<T>(x: AnyObject) -> T /// Returns: `nonEmpty!` /// /// Requires: `nonEmpty != nil`. In particular, in -O builds, no test /// is performed to ensure that `nonEmpty` actually is non-nil. /// /// .. Danger:: trades safety for performance. Use `unsafeUnwrap` /// only when `nonEmpty!` has proven to be a performance problem and /// you are confident that, always, `nonEmpty != nil`. It is better /// than an `unsafeBitCast` because it's more restrictive, and /// because checking is still performed in debug builds. @inline(__always) func unsafeUnwrap<T>(nonEmpty: T?) -> T /// Evaluate `f()` and return its result, ensuring that `x` is not /// destroyed before f returns. func withExtendedLifetime<T, Result>(x: T, f: @noescape () -> Result) -> Result /// Evaluate `f(x)` and return its result, ensuring that `x` is not /// destroyed before f returns. func withExtendedLifetime<T, Result>(x: T, f: @noescape T -> Result) -> Result /// Invokes `body` with an `UnsafeMutablePointer` to `arg` and returns the /// result. Useful for calling Objective-C APIs that take "in/out" /// parameters (and default-constructible "out" parameters) by pointer func withUnsafeMutablePointer<T, Result>(inout arg: T, body: @noescape UnsafeMutablePointer<T> -> Result) -> Result /// Like `withUnsafeMutablePointer`, but passes pointers to `arg0`, `arg1`, /// and `arg2`. func withUnsafeMutablePointers<A0, A1, A2, Result>(inout arg0: A0, inout arg1: A1, inout arg2: A2, body: @noescape (UnsafeMutablePointer<A0>, UnsafeMutablePointer<A1>, UnsafeMutablePointer<A2>) -> Result) -> Result /// Like `withUnsafeMutablePointer`, but passes pointers to `arg0` and `arg1`. func withUnsafeMutablePointers<A0, A1, Result>(inout arg0: A0, inout arg1: A1, body: @noescape (UnsafeMutablePointer<A0>, UnsafeMutablePointer<A1>) -> Result) -> Result /// Invokes `body` with an `UnsafePointer` to `arg` and returns the /// result. Useful for calling Objective-C APIs that take "in/out" /// parameters (and default-constructible "out" parameters) by pointer func withUnsafePointer<T, Result>(inout arg: T, body: @noescape UnsafePointer<T> -> Result) -> Result /// Like `withUnsafePointer`, but passes pointers to `arg0`, `arg1`, /// and `arg2`. func withUnsafePointers<A0, A1, A2, Result>(inout arg0: A0, inout arg1: A1, inout arg2: A2, body: @noescape (UnsafePointer<A0>, UnsafePointer<A1>, UnsafePointer<A2>) -> Result) -> Result /// Like `withUnsafePointer`, but passes pointers to `arg0` and `arg1`. func withUnsafePointers<A0, A1, Result>(inout arg0: A0, inout arg1: A1, body: @noescape (UnsafePointer<A0>, UnsafePointer<A1>) -> Result) -> Result /// Invoke `f` with a C `va_list` argument derived from `args`. func withVaList<R>(args: [CVarArgType], f: @noescape CVaListPointer -> R) -> R /// Invoke `f` with a C `va_list` argument derived from `builder`. func withVaList<R>(builder: VaListBuilder, f: @noescape CVaListPointer -> R) -> R /// A sequence of pairs built out of two underlying sequences, where /// the elements of the `i`\ th pair are the `i`\ th elements of each /// underlying sequence. func zip<S0 : SequenceType, S1 : SequenceType>(s0: S0, s1: S1) -> Zip2<S0, S1> func |(lhs: UInt16, rhs: UInt16) -> UInt16 func |(lhs: Int16, rhs: Int16) -> Int16 func |(lhs: Int8, rhs: Int8) -> Int8 func |(lhs: UInt8, rhs: UInt8) -> UInt8 func |<T : _RawOptionSetType>(a: T, b: T) -> T func |(lhs: Int, rhs: Int) -> Int func |(lhs: UInt, rhs: UInt) -> UInt func |(lhs: Int64, rhs: Int64) -> Int64 func |(lhs: UInt32, rhs: UInt32) -> UInt32 func |(lhs: UInt64, rhs: UInt64) -> UInt64 func |(lhs: Int32, rhs: Int32) -> Int32 func |=(inout lhs: Int32, rhs: Int32) func |=(inout lhs: UInt32, rhs: UInt32) func |=(inout lhs: Int16, rhs: Int16) func |=(inout lhs: UInt16, rhs: UInt16) func |=(inout lhs: Int8, rhs: Int8) func |=(inout lhs: UInt8, rhs: UInt8) func |=(inout lhs: Int64, rhs: Int64) func |=(inout lhs: UInt, rhs: UInt) func |=(inout lhs: Int, rhs: Int) func |=<T : BitwiseOperationsType>(inout lhs: T, rhs: T) func |=(inout lhs: UInt64, rhs: UInt64) /// If `lhs` is `true`, return it. Otherwise, evaluate `rhs` and /// return its `boolValue`. @inline(__always) func ||<T : BooleanType, U : BooleanType>(lhs: T, rhs: @autoclosure () -> U) -> Bool func ||<T : BooleanType>(lhs: T, rhs: @autoclosure () -> Bool) -> Bool prefix func ~(rhs: Int) -> Int prefix func ~(rhs: UInt) -> UInt prefix func ~(rhs: Int64) -> Int64 prefix func ~(rhs: UInt64) -> UInt64 prefix func ~(rhs: Int32) -> Int32 prefix func ~(rhs: UInt32) -> UInt32 prefix func ~(rhs: Int16) -> Int16 prefix func ~(rhs: UInt16) -> UInt16 prefix func ~(rhs: Int8) -> Int8 prefix func ~(rhs: UInt8) -> UInt8 prefix func ~<T : _RawOptionSetType>(a: T) -> T /// Returns `true` iff `pattern` contains `value` func ~=<I : IntervalType>(pattern: I, value: I.Bound) -> Bool func ~=<T>(lhs: _OptionalNilComparisonType, rhs: T?) -> Bool func ~=<T : Equatable>(a: T, b: T) -> Bool func ~=<I : ForwardIndexType where I : Comparable>(pattern: Range<I>, value: I) -> Bool
f1f58af01142716f43299c411aa169fb
31.14262
332
0.662264
false
false
false
false
xmartlabs/XLForm
refs/heads/master
Examples/Swift/SwiftExample/SelectorsFormViewController.swift
mit
1
// // SelectorsFormViewController.swift // XLForm ( https://github.com/xmartlabs/XLForm ) // // Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.com ) // // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import MapKit // Mark - NSValueTransformer class NSArrayValueTrasformer : ValueTransformer { override class func transformedValueClass() -> AnyClass { return NSString.self } override class func allowsReverseTransformation() -> Bool { return false } override func transformedValue(_ value: Any?) -> Any? { if let arrayValue = value as? Array<AnyObject> { return String(format: "%d Item%@", arrayValue.count, arrayValue.count > 1 ? "s" : "") } else if let stringValue = value as? String { return String(format: "%@ - ) - Transformed", stringValue) } return nil } } class ISOLanguageCodesValueTranformer : ValueTransformer { override class func transformedValueClass() -> AnyClass { return NSString.self } override class func allowsReverseTransformation() -> Bool { return false } override func transformedValue(_ value: Any?) -> Any? { if let stringValue = value as? String { return (Locale.current as NSLocale).displayName(forKey: NSLocale.Key.languageCode, value: stringValue) } return nil } } // Mark - SelectorsFormViewController class SelectorsFormViewController : XLFormViewController { fileprivate struct Tags { static let Push = "selectorPush" static let Popover = "selectorPopover" static let ActionSheet = "selectorActionSheet" static let AlertView = "selectorAlertView" static let PickerView = "selectorPickerView" static let Picker = "selectorPicker" static let PickerViewInline = "selectorPickerViewInline" static let MultipleSelector = "multipleSelector" static let MultipleSelectorPopover = "multipleSelectorPopover" static let DynamicSelectors = "dynamicSelectors" static let CustomSelectors = "customSelectors" static let SelectorWithSegueId = "selectorWithSegueId" static let SelectorWithSegueClass = "selectorWithSegueClass" static let SelectorWithNibName = "selectorWithNibName" static let SelectorWithStoryboardId = "selectorWithStoryboardId" } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) initializeForm() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) initializeForm() } override func viewDidLoad() { super.viewDidLoad() let barButton = UIBarButtonItem(title: "Disable", style: .plain, target: self, action: #selector(SelectorsFormViewController.disableEnable(_:))) barButton.possibleTitles = Set(["Disable", "Enable"]) navigationItem.rightBarButtonItem = barButton } @objc func disableEnable(_ button : UIBarButtonItem) { form.isDisabled = !form.isDisabled button.title = form.isDisabled ? "Enable" : "Disable" tableView.endEditing(true) tableView.reloadData() } func initializeForm() { let form : XLFormDescriptor var section : XLFormSectionDescriptor var row : XLFormRowDescriptor form = XLFormDescriptor(title: "Selectors") section = XLFormSectionDescriptor.formSection(withTitle: "Selectors") section.footerTitle = "SelectorsFormViewController.swift" form.addFormSection(section) // Selector Push row = XLFormRowDescriptor(tag: Tags.Push, rowType:XLFormRowDescriptorTypeSelectorPush, title:"Push") row.selectorOptions = [XLFormOptionsObject(value: 0, displayText: "Option 1")!, XLFormOptionsObject(value: 1, displayText:"Option 2")!, XLFormOptionsObject(value: 2, displayText:"Option 3")!, XLFormOptionsObject(value: 3, displayText:"Option 4")!, XLFormOptionsObject(value: 4, displayText:"Option 5")! ] row.value = XLFormOptionsObject(value: 1, displayText:"Option 2") section.addFormRow(row) // Selector Popover if (UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad){ row = XLFormRowDescriptor(tag: Tags.Popover, rowType:XLFormRowDescriptorTypeSelectorPopover, title:"PopOver") row.selectorOptions = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5", "Option 6"] row.value = "Option 2" section.addFormRow(row) } // Selector Action Sheet row = XLFormRowDescriptor(tag :Tags.ActionSheet, rowType:XLFormRowDescriptorTypeSelectorActionSheet, title:"Sheet") row.selectorOptions = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"] row.value = "Option 3" section.addFormRow(row) // Selector Alert View row = XLFormRowDescriptor(tag: Tags.AlertView, rowType:XLFormRowDescriptorTypeSelectorAlertView, title:"Alert View") row.selectorOptions = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"] row.value = "Option 3" section.addFormRow(row) // Selector Picker View row = XLFormRowDescriptor(tag: Tags.PickerView, rowType:XLFormRowDescriptorTypeSelectorPickerView, title:"Picker View") row.selectorOptions = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"] row.value = "Option 4" section.addFormRow(row) // --------- Fixed Controls section = XLFormSectionDescriptor.formSection(withTitle: "Fixed Controls") form.addFormSection(section) row = XLFormRowDescriptor(tag: Tags.Picker, rowType:XLFormRowDescriptorTypePicker) row.selectorOptions = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5"] row.value = "Option 1" section.addFormRow(row) // --------- Inline Selectors section = XLFormSectionDescriptor.formSection(withTitle: "Inline Selectors") form.addFormSection(section) row = XLFormRowDescriptor(tag: Tags.MultipleSelector, rowType:XLFormRowDescriptorTypeSelectorPickerViewInline, title:"Inline Picker View") row.selectorOptions = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5", "Option 6"] row.value = "Option 6" section.addFormRow(row) // --------- MultipleSelector section = XLFormSectionDescriptor.formSection(withTitle: "Multiple Selectors") form.addFormSection(section) row = XLFormRowDescriptor(tag: Tags.MultipleSelector, rowType:XLFormRowDescriptorTypeMultipleSelector, title:"Multiple Selector") row.selectorOptions = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5", "Option 6"] row.value = ["Option 1", "Option 3", "Option 4", "Option 5", "Option 6"] section.addFormRow(row) // Multiple selector with value tranformer row = XLFormRowDescriptor(tag: Tags.MultipleSelector, rowType:XLFormRowDescriptorTypeMultipleSelector, title:"Multiple Selector") row.selectorOptions = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5", "Option 6"] row.value = ["Option 1", "Option 3", "Option 4", "Option 5", "Option 6"] row.valueTransformer = NSArrayValueTrasformer.self section.addFormRow(row) // Language multiple selector row = XLFormRowDescriptor(tag: Tags.MultipleSelector, rowType:XLFormRowDescriptorTypeMultipleSelector, title:"Multiple Selector") row.selectorOptions = Locale.isoLanguageCodes row.selectorTitle = "Languages" row.valueTransformer = ISOLanguageCodesValueTranformer.self row.value = Locale.preferredLanguages section.addFormRow(row) if UIDevice.current.userInterfaceIdiom == .pad { // Language multiple selector popover row = XLFormRowDescriptor(tag: Tags.MultipleSelectorPopover, rowType:XLFormRowDescriptorTypeMultipleSelectorPopover, title:"Multiple Selector PopOver") row.selectorOptions = Locale.isoLanguageCodes row.valueTransformer = ISOLanguageCodesValueTranformer.self row.value = Locale.preferredLanguages section.addFormRow(row) } // --------- Dynamic Selectors section = XLFormSectionDescriptor.formSection(withTitle: "Dynamic Selectors") form.addFormSection(section) row = XLFormRowDescriptor(tag: Tags.DynamicSelectors, rowType:XLFormRowDescriptorTypeButton, title:"Dynamic Selectors") row.action.viewControllerClass = DynamicSelectorsFormViewController.self section.addFormRow(row) // --------- Custom Selectors section = XLFormSectionDescriptor.formSection(withTitle: "Custom Selectors") form.addFormSection(section) row = XLFormRowDescriptor(tag: Tags.CustomSelectors, rowType:XLFormRowDescriptorTypeButton, title:"Custom Selectors") row.action.viewControllerClass = CustomSelectorsFormViewController.self section.addFormRow(row) // --------- Selector definition types section = XLFormSectionDescriptor.formSection(withTitle: "Selectors") form.addFormSection(section) // selector with segue class row = XLFormRowDescriptor(tag: Tags.SelectorWithSegueClass, rowType: XLFormRowDescriptorTypeSelectorPush, title: "Selector with Segue Class") row.action.formSegueClass = NSClassFromString("UIStoryboardPushSegue") row.action.viewControllerClass = MapViewController.self row.valueTransformer = CLLocationValueTrasformer.self row.value = CLLocation(latitude: -33, longitude: -56) section.addFormRow(row) // selector with SegueId row = XLFormRowDescriptor(tag: Tags.SelectorWithSegueId, rowType: XLFormRowDescriptorTypeSelectorPush, title: "Selector with Segue Idenfifier") row.action.formSegueIdentifier = "MapViewControllerSegue"; row.valueTransformer = CLLocationValueTrasformer.self row.value = CLLocation(latitude: -33, longitude: -56) section.addFormRow(row) // selector using StoryboardId row = XLFormRowDescriptor(tag: Tags.SelectorWithStoryboardId, rowType: XLFormRowDescriptorTypeSelectorPush, title: "Selector with StoryboardId") row.action.viewControllerStoryboardId = "MapViewController"; row.valueTransformer = CLLocationValueTrasformer.self row.value = CLLocation(latitude: -33, longitude: -56) section.addFormRow(row) // selector with NibName row = XLFormRowDescriptor(tag: Tags.SelectorWithNibName, rowType: XLFormRowDescriptorTypeSelectorPush, title: "Selector with NibName") row.action.viewControllerNibName = "MapViewController" row.valueTransformer = CLLocationValueTrasformer.self row.value = CLLocation(latitude: -33, longitude: -56) section.addFormRow(row) self.form = form } override func storyboard(forRow formRow: XLFormRowDescriptor!) -> UIStoryboard! { return UIStoryboard(name: "iPhoneStoryboard", bundle:nil) } }
c929ae0d3b87cd21f732483e5d2405a5
43.41115
163
0.666641
false
false
false
false
ErikOwen/Gradebook
refs/heads/master
Gradebook/LoginViewController.swift
mit
1
// // ViewController.swift // Gradebook // // Created by Erik Owen on 5/5/15. // Copyright (c) 2015 Erik Owen. All rights reserved. // import UIKit class LoginViewController: UIViewController { var loader: GradebookLoader? @IBAction func loginButtonPressed(sender: AnyObject) { println("Login button pressed"); } @IBAction func testButtonPressed(sender: AnyObject) { println("Test button pressed"); usernameInput.text = "test"; passwordInput.text = "sadf35cx90"; baseUrlInput.text = "https://users.csc.calpoly.edu/~bellardo/cgi-bin/test/grades.json"; } @IBOutlet weak var cpImage: UIImageView! @IBOutlet weak var usernameInput: UITextField! @IBOutlet weak var passwordInput: UITextField! @IBOutlet weak var baseUrlInput: UITextField! override func viewDidLoad() { super.viewDidLoad() /*Sets the background image*/ cpImage.image = UIImage(named: "cp_logo"); /*Makes sure the password input is hidden*/ passwordInput.secureTextEntry = true; self.title = "Cal Poly Login" } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated); usernameInput.text = "" passwordInput.text = "" baseUrlInput.text = "https://users.csc.calpoly.edu/~bellardo/cgi-bin/grades.json" } func presentErrorPopUp() { let alertController = UIAlertController(title: "Wrong Base URL", message: "The base URL must be either https://users.csc.calpoly.edu/~bellardo/cgi-bin/grades.json or https://users.csc.calpoly.edu/~bellardo/cgi-bin/test/grades.json", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } func presentLoginErrorPopUp() { let alertController = UIAlertController(title: "Login Error", message: "Sorry, the login credentials you provided were not recognized", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } override func shouldPerformSegueWithIdentifier(identifier: String!, sender: AnyObject!) -> Bool { if identifier == "loginToSectionSegue" { println("Segue check worked!") println("default base url is: " + baseUrlInput.text); var baseURL = baseUrlInput.text var name = usernameInput.text var password = passwordInput.text if(baseURL != "https://users.csc.calpoly.edu/~bellardo/cgi-bin/grades.json" && baseURL != "https://users.csc.calpoly.edu/~bellardo/cgi-bin/test/grades.json") { presentErrorPopUp() return false; } else { if loader!.loginWithUsername(name, password: password, baseURL: baseURL) { println("Auth worked!") return true; } else { println("Auth failed!") presentLoginErrorPopUp() return false; } } } return false; } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "loginToSectionSegue" { let dest: SectionTableViewController = segue.destinationViewController as! SectionTableViewController dest.loader = loader self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Logout", style: UIBarButtonItemStyle.Plain, target: nil, action: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
d7136165c6f0b6697d7d666b779407ee
33.471074
212
0.613522
false
false
false
false
alblue/swift
refs/heads/master
test/stdlib/KVOKeyPaths.swift
apache-2.0
3
// RUN: %target-run-simple-swift | %FileCheck %s // REQUIRES: executable_test // REQUIRES: objc_interop import Foundation struct Guts { var internalValue = 42 var value: Int { get { return internalValue } } init(value: Int) { internalValue = value } init() { } } class Target : NSObject, NSKeyValueObservingCustomization { // This dynamic property is observed by KVO @objc dynamic var objcValue: String @objc dynamic var objcValue2: String { willSet { willChangeValue(for: \.objcValue2) } didSet { didChangeValue(for: \.objcValue2) } } @objc dynamic var objcValue3: String // This Swift-typed property causes vtable usage on this class. var swiftValue: Guts override init() { self.swiftValue = Guts() self.objcValue = "" self.objcValue2 = "" self.objcValue3 = "" super.init() } static func keyPathsAffectingValue(for key: AnyKeyPath) -> Set<AnyKeyPath> { if (key == \Target.objcValue) { return [\Target.objcValue2, \Target.objcValue3] } else { return [] } } static func automaticallyNotifiesObservers(for key: AnyKeyPath) -> Bool { if key == \Target.objcValue2 || key == \Target.objcValue3 { return false } return true } func print() { Swift.print("swiftValue \(self.swiftValue.value), objcValue \(objcValue)") } } class ObserverKVO : NSObject { var target: Target? var observation: NSKeyValueObservation? = nil override init() { target = nil; super.init() } func observeTarget(_ target: Target) { self.target = target observation = target.observe(\.objcValue) { (object, change) in Swift.print("swiftValue \(object.swiftValue.value), objcValue \(object.objcValue)") } } func removeTarget() { observation!.invalidate() } } var t2 = Target() var o2 = ObserverKVO() print("unobserved 2") t2.objcValue = "one" t2.objcValue = "two" print("registering observer 2") o2.observeTarget(t2) print("Now witness the firepower of this fully armed and operational panopticon!") t2.objcValue = "three" t2.objcValue = "four" t2.swiftValue = Guts(value: 13) t2.objcValue2 = "six" //should fire t2.objcValue3 = "nothing" //should not fire o2.removeTarget() t2.objcValue = "five" //make sure that we don't crash or keep posting changes if you deallocate an observation after invalidating it print("target removed") // CHECK: registering observer 2 // CHECK-NEXT: Now witness the firepower of this fully armed and operational panopticon! // CHECK-NEXT: swiftValue 42, objcValue three // CHECK-NEXT: swiftValue 42, objcValue four // CHECK-NEXT: swiftValue 13, objcValue four // CHECK-NEXT: swiftValue 13, objcValue four // CHECK-NEXT: swiftValue 13, objcValue four // CHECK-NEXT: target removed
619c39dc262d1ee3a45a42c67db9d966
26.099099
132
0.634309
false
false
false
false
Czajnikowski/TrainTrippin
refs/heads/master
LibrarySample/Pods/RxSwift/RxSwift/Schedulers/VirtualTimeConverterType.swift
mit
3
// // VirtualTimeConverterType.swift // RxSwift // // Created by Krunoslav Zaher on 12/23/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // import Foundation /** Parametrization for virtual time used by `VirtualTimeScheduler`s. */ public protocol VirtualTimeConverterType { /** Virtual time unit used that represents ticks of virtual clock. */ associatedtype VirtualTimeUnit /** Virtual time unit used to represent differences of virtual times. */ associatedtype VirtualTimeIntervalUnit /** Converts virtual time to real time. - parameter virtualTime: Virtual time to convert to `Date`. - returns: `Date` corresponding to virtual time. */ func convertFromVirtualTime(_ virtualTime: VirtualTimeUnit) -> RxTime /** Converts real time to virtual time. - parameter time: `Date` to convert to virtual time. - returns: Virtual time corresponding to `Date`. */ func convertToVirtualTime(_ time: RxTime) -> VirtualTimeUnit /** Converts from virtual time interval to `NSTimeInterval`. - parameter virtualTimeInterval: Virtual time interval to convert to `NSTimeInterval`. - returns: `NSTimeInterval` corresponding to virtual time interval. */ func convertFromVirtualTimeInterval(_ virtualTimeInterval: VirtualTimeIntervalUnit) -> RxTimeInterval /** Converts from virtual time interval to `NSTimeInterval`. - parameter timeInterval: `NSTimeInterval` to convert to virtual time interval. - returns: Virtual time interval corresponding to time interval. */ func convertToVirtualTimeInterval(_ timeInterval: RxTimeInterval) -> VirtualTimeIntervalUnit /** Offsets virtual time by virtual time interval. - parameter time: Virtual time. - parameter offset: Virtual time interval. - returns: Time corresponding to time offsetted by virtual time interval. */ func offsetVirtualTime(_ time: VirtualTimeUnit, offset: VirtualTimeIntervalUnit) -> VirtualTimeUnit /** This is aditional abstraction because `Date` is unfortunately not comparable. Extending `Date` with `Comparable` would be too risky because of possible collisions with other libraries. */ func compareVirtualTime(_ lhs: VirtualTimeUnit, _ rhs: VirtualTimeUnit) -> VirtualTimeComparison } /** Virtual time comparison result. This is aditional abstraction because `Date` is unfortunately not comparable. Extending `Date` with `Comparable` would be too risky because of possible collisions with other libraries. */ public enum VirtualTimeComparison { /** lhs < rhs. */ case lessThan /** lhs == rhs. */ case equal /** lhs > rhs. */ case greaterThan } extension VirtualTimeComparison { /** lhs < rhs. */ var lessThen: Bool { return self == .lessThan } /** lhs > rhs */ var greaterThan: Bool { return self == .greaterThan } /** lhs == rhs */ var equal: Bool { return self == .equal } }
dd8dfa6367993e7ac4310b74a3d9810b
26.156522
111
0.675953
false
false
false
false
4faramita/TweeBox
refs/heads/master
TweeBox/VideoViewerViewController.swift
mit
1
// // VideoViewerViewController.swift // TweeBox // // Created by 4faramita on 2017/8/13. // Copyright © 2017年 4faramita. All rights reserved. // import UIKit import BMPlayer class VideoViewerViewController: PannableViewController { private var isInLandscapeMode: Bool! public var tweetMedia: TweetMedia! { didSet { // BMPlayerConf.enableBrightnessGestures = false // BMPlayerConf.enableVolumeGestures = false let player = BMPlayer() player.center = view.center view.addSubview(player) player.snp.makeConstraints { (make) in // make.centerY.equalTo(self.view.snp.centerY) // make.left.right.equalTo(self.view) make.center.equalTo(self.view) make.leading.greaterThanOrEqualTo(0) make.trailing.greaterThanOrEqualTo(0) make.top.greaterThanOrEqualTo(0) make.bottom.greaterThanOrEqualTo(0) let aspectRatio = CGFloat((tweetMedia.videoInfo?.aspectRatio[1])!) / CGFloat((tweetMedia.videoInfo?.aspectRatio[0])!) make.height.equalTo(player.snp.width).multipliedBy(aspectRatio).priority(750) } player.backBlock = { [unowned self] (wtf) in let _ = self.presentingViewController?.dismiss(animated: true) } let asset = BMPlayerResource(url: (tweetMedia.videoInfo?.variants?[0].url)!, name: tweetMedia.extAltText ?? "") player.setVideo(resource: asset) } } // override var prefersStatusBarHidden: Bool { // return true // } // override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation { // return .slide // } override func viewWillAppear(_ animated: Bool) { let size: CGSize = UIScreen.main.bounds.size if size.width / size.height > 1 { isInLandscapeMode = true } else { isInLandscapeMode = false } } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { if (size.width / size.height > 1) { isInLandscapeMode = true } else { isInLandscapeMode = false } } }
e6c8e4b6627d017f0b5b4b52407d9557
32.985507
133
0.596588
false
false
false
false