repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
tarrgor/LctvSwift | Sources/LctvVideo.swift | 1 | 1359 | //
// LctvVideo.swift
// Pods
//
//
//
import Foundation
import SwiftyJSON
public struct LctvVideo : JSONInitializable {
public var url: String?
public var slug: String?
public var user: String?
public var title: String?
public var description: String?
public var codingCategory: String?
public var difficulty: String?
public var language: String?
public var productType: String?
public var creationTime: String?
public var duration: Int?
public var region: String?
public var viewersOverall: Int?
public var viewingUrls: Array<String> = []
public var thumbnailUrl: String?
public init(json: JSON) {
url = json["url"].string
slug = json["slug"].string
user = json["user"].string
title = json["title"].string
description = json["description"].string
codingCategory = json["coding_category"].string
difficulty = json["difficulty"].string
language = json["language"].string
productType = json["product_type"].string
creationTime = json["creation_time"].string
duration = json["duration"].int
region = json["region"].string
viewersOverall = json["viewers_overall"].int
thumbnailUrl = json["thumbnail_url"].string
if let urls = json["viewing_urls"].arrayObject {
urls.forEach({ object in
viewingUrls.append(object as! String)
})
}
}
}
| mit | f5c9df9ce8ece308491a511cd5ae1f56 | 25.647059 | 52 | 0.681383 | 4.143293 | false | false | false | false |
Digipolitan/perfect-middleware-swift | Sources/PerfectMiddleware/RouterMiddleware.swift | 1 | 6283 | import PerfectLib
import PerfectHTTP
import PerfectHTTPServer
/**
* The middleware router for the routing of requests
* @author Benoit BRIATTE http://www.digipolitan.com
* @copyright 2017 Digipolitan. All rights reserved.
*/
open class RouterMiddleware {
/**
* Events for middleware
*/
public enum Event {
/** Call the middleware before all others */
case beforeAll
/** Call the middleware after all others */
case afterAll
/** Call the middleware if no routes were found */
case notFound
}
private var beforeAll: [Middleware]
private var afterAll: [Middleware]
private var notFound: Middleware?
private var children: [String: RouterMiddleware]
private var registry: RouteMiddlewareRegistry
private var errorHandler: ErrorHandler?
private var verbose: Bool;
public static func sanitize(path: String) -> String {
guard path.count > 0 && path != "/" else {
return "/"
}
var res = path;
let last = res.endIndex
let separator = Character(UnicodeScalar(47))
if res[res.index(before: last)] == separator {
res.removeLast()
}
let first = res.startIndex
if res[first] != separator {
res.insert(separator, at: first)
}
return res
}
public convenience init() {
self.init(verbose: false)
}
public init(verbose: Bool) {
self.beforeAll = [Middleware]()
self.afterAll = [Middleware]()
self.children = [String: RouterMiddleware]()
self.registry = RouteMiddlewareRegistry()
self.verbose = verbose
}
@discardableResult
public func use(event: Event, handler: @escaping MiddlewareHandler) -> Self {
return self.use(event: event, middleware: MiddlewareWrapper(handler: handler))
}
@discardableResult
public func use(event: Event, middleware: Middleware) -> Self {
switch event {
case .beforeAll:
self.beforeAll.append(middleware)
case .afterAll:
self.afterAll.append(middleware)
case .notFound:
self.notFound = middleware
}
return self
}
@discardableResult
public func use(errorHandler: @escaping ErrorHandler) -> Self {
self.errorHandler = errorHandler
return self
}
@discardableResult
public func use(path: String, child router: RouterMiddleware) -> Self {
self.children[RouterMiddleware.sanitize(path: path)] = router
return self
}
public func get(path: String) -> MiddlewareBinder {
return self.binder(method: .get, path: path)
}
public func post(path: String) -> MiddlewareBinder {
return self.binder(method: .post, path: path)
}
public func put(path: String) -> MiddlewareBinder {
return self.binder(method: .put, path: path)
}
public func delete(path: String) -> MiddlewareBinder {
return self.binder(method: .delete, path: path)
}
public func options(path: String) -> MiddlewareBinder {
return self.binder(method: .options, path: path)
}
public func methods(_ methods: [HTTPMethod], path: String) -> MiddlewareBinder {
return CompositeMiddlewareBinder(children: methods.map { method -> MiddlewareBinder in
return self.binder(method: method, path: path)
})
}
public func binder(method: HTTPMethod, path: String) -> MiddlewareBinder {
return self.registry.findOrCreate(method: method, path: path)
}
fileprivate func getRoutes(path: String = "", beforeAll: [Middleware] = [], afterAll: [Middleware] = [], verbose: Bool = false, errorHandler: ErrorHandler? = nil) -> Routes {
var routes = Routes(baseUri: path)
let depthBeforeAll = beforeAll + self.beforeAll
let depthAfterAll = self.afterAll + afterAll
let curErrorHandler = (self.errorHandler != nil) ? self.errorHandler : errorHandler
let curVerbose = (verbose == true) ? verbose : self.verbose
self.registry.binders.forEach { (method: HTTPMethod, value: [String : RouteMiddlewareBinder]) in
value.forEach({ (key: String, value: RouteMiddlewareBinder) in
let middlewares = depthBeforeAll + value.middlewares + depthAfterAll
if curVerbose {
Log.info(message: "HTTP Server listen \(method.description) on \(path)\(key)")
}
routes.add(method: method, uri: key, handler: { request, response in
MiddlewareIterator(request: request,
response: response,
middlewares: middlewares,
errorHandler: curErrorHandler).next()
})
})
}
self.children.forEach { (key: String, value: RouterMiddleware) in
routes.add(value.getRoutes(path: path + key,
beforeAll: depthBeforeAll,
afterAll: depthAfterAll,
verbose: curVerbose,
errorHandler: curErrorHandler
))
}
if let notFound = self.notFound {
var notFoundMiddlewares = depthBeforeAll
notFoundMiddlewares.append(notFound)
notFoundMiddlewares.append(contentsOf: depthAfterAll)
if curVerbose {
Log.info(message: "HTTP Server listen 404 from " + (path == "" ? "/" : path));
}
routes.add(uri: "**", handler: { request, response in
MiddlewareIterator(request: request,
response: response,
middlewares: notFoundMiddlewares,
errorHandler: curErrorHandler).next()
})
}
return routes
}
}
/**
* Add RouterMiddleware supports for HTTPServer
*/
public extension HTTPServer {
/**
* Register the router inside the HttpServer by adding all routes
* @param router The router midddleware to register
*/
func use(router: RouterMiddleware) {
self.addRoutes(router.getRoutes())
}
}
| bsd-3-clause | 8a6b8d255a52ad765a894b130c711329 | 32.962162 | 178 | 0.596053 | 4.840524 | false | false | false | false |
DroidsOnRoids/RxSwiftExamples | Libraries Usage/RxDataSourcesExample/RxDataSourcesExample/ViewController.swift | 1 | 2884 | //
// ViewController.swift
// RxDataSourcesExample
//
// Created by Lukasz Mroz on 08.02.2016.
// Copyright © 2016 Droids on Roids. All rights reserved.
//
//
// This is basically the copy of RxSwiftExample, but using RxDataSources and NSObject-Rx,
// from the awesome RxSwiftCommunity. The first module, RxDataSources, allows to easily
// use blocks and bind them to table views instead of using large delegate methods. The
// second one, NSObject-Rx, is just a wrapper that you don't have to everytime write
// DisposableBags, Rx will take care of it for you!
//
import UIKit
import RxSwift
import RxCocoa
import RxDataSources
import NSObject_Rx
class ViewController: UIViewController {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var searchBar: UISearchBar!
let dataSource = RxTableViewSectionedReloadDataSource<DefaultSection>()
var shownCitiesSection: DefaultSection!
var allCities = [String]()
var sections = PublishSubject<[DefaultSection]>()
override func viewDidLoad() {
super.viewDidLoad()
setup()
}
func setup() {
allCities = ["New York", "London", "Oslo", "Warsaw", "Berlin", "Praga"]
shownCitiesSection = DefaultSection(header: "Cities", items: allCities.toItems(), updated: Date())
sections.onNext([shownCitiesSection])
dataSource.configureCell = { (_, tableView, indexPath, index) in
let cell = tableView.dequeueReusableCell(withIdentifier: "cityPrototypeCell", for: indexPath)
cell.textLabel?.text = self.shownCitiesSection.items[indexPath.row].title
return cell
}
sections
.asObservable()
.bindTo(tableView.rx.items(dataSource: dataSource))
.addDisposableTo(rx_disposeBag) // Instead of creating the bag again and again, use the extension NSObject_rx
searchBar
.rx.text
.filter { $0 != nil }
.map { $0! }
.debounce(0.5, scheduler: MainScheduler.instance)
.distinctUntilChanged()
.subscribe(onNext: { [unowned self] query in
let items: [String]
if query.characters.count > 0 {
items = self.allCities.filter { $0.hasPrefix(query) }
} else {
items = self.allCities
}
self.shownCitiesSection = DefaultSection(
original: self.shownCitiesSection,
items: items.toItems()
)
self.sections.onNext([self.shownCitiesSection])
})
.addDisposableTo(rx_disposeBag)
}
}
extension Collection where Self.Iterator.Element == String {
func toItems() -> [DefaultItem] {
return self.map { DefaultItem(title: $0, dateChanged: Date()) }
}
}
| mit | 721294e7f445ab35fa8bfd2fefe3491c | 34.592593 | 121 | 0.622268 | 4.69544 | false | false | false | false |
jemartti/Hymnal | Hymnal/HomeViewController.swift | 1 | 9449 | //
// HomeViewController.swift
// Hymnal
//
// Created by Jacob Marttinen on 4/30/17.
// Copyright © 2017 Jacob Marttinen. All rights reserved.
//
import UIKit
// MARK: - HomeViewController: UIViewController
class HomeViewController: UIViewController {
// MARK: Properties
let appDelegate = UIApplication.shared.delegate as! AppDelegate
var impactGenerator: UIImpactFeedbackGenerator? = nil
var selectionGenerator: UISelectionFeedbackGenerator? = nil
// MARK: Outlets
@IBOutlet weak var subView: UIView!
@IBOutlet weak var openHymnButton: UIButton!
@IBOutlet weak var hymnNumberInput: UITextField!
@IBOutlet weak var directoryButton: UIButton!
@IBOutlet weak var scheduleButton: UIButton!
// MARK: Actions
@IBAction func hymnNumberSent(_ sender: Any) {
doneButtonAction()
}
@IBAction func directorySelect(_ sender: Any) {
loadDirectory()
}
@IBAction func schedulesSelect(_ sender: Any) {
loadSchedule()
}
// MARK: Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
loadSettings()
initialiseUI()
loadHymnalFile()
loadDirectoryFile()
}
// MARK: State Handling
private func loadSettings() {
if !UserDefaults.standard.bool(forKey: "hasLaunchedBefore") {
appDelegate.theme = .light
appDelegate.hymnFontSize = CGFloat(24.0)
UserDefaults.standard.set(true, forKey: "hasLaunchedBefore")
UserDefaults.standard.set(appDelegate.theme, forKey: "theme")
UserDefaults.standard.set(Double(appDelegate.hymnFontSize), forKey: "hymnFontSize")
UserDefaults.standard.synchronize()
} else {
if let rawTheme = Constants.Themes(rawValue: UserDefaults.standard.integer(forKey: "theme")) {
appDelegate.theme = rawTheme
} else {
appDelegate.theme = .light
}
appDelegate.hymnFontSize = CGFloat(UserDefaults.standard.double(forKey: "hymnFontSize"))
if !appDelegate.hymnFontSize.isFinite || appDelegate.hymnFontSize <= 0 {
appDelegate.hymnFontSize = CGFloat(24.0)
UserDefaults.standard.set(Double(appDelegate.hymnFontSize), forKey: "hymnFontSize")
UserDefaults.standard.synchronize()
}
}
}
// MARK: Data Management
private func loadHymnalFile() {
if let path = Bundle.main.path(forResource: "hymns", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
var parsedResult: AnyObject! = nil
do {
parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as AnyObject
} catch {
let userInfo = [NSLocalizedDescriptionKey : "Could not parse the hymnal file data as JSON: '\(data)'"]
throw NSError(domain: "HomeViewController", code: 1, userInfo: userInfo)
}
Hymnal.hymnal = Hymnal(dictionary: parsedResult as! [String:AnyObject])
} catch _ as NSError {
alertUserOfFailure(message: "Hymnal file loading failed.")
}
}
}
private func loadDirectoryFile() {
if let path = Bundle.main.path(forResource: "directory", ofType: "json") {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
var parsedResult: AnyObject! = nil
do {
parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as AnyObject
} catch {
let userInfo = [NSLocalizedDescriptionKey : "Could not parse the directory file data as JSON: '\(data)'"]
throw NSError(domain: "HomeViewController", code: 1, userInfo: userInfo)
}
Directory.directory = Directory(dictionary: parsedResult as! [String:[String:AnyObject]])
} catch _ as NSError {
alertUserOfFailure(message: "Directory file loading failed.")
}
}
}
// UI+UX Functionality
private func initialiseUI() {
view.backgroundColor = .white
subView.backgroundColor = Constants.UI.WildSand
openHymnButton.backgroundColor = .white
openHymnButton.setTitleColor(Constants.UI.Armadillo, for: .normal)
let placeholder = NSAttributedString(
string: "000",
attributes: [NSAttributedString.Key.foregroundColor: Constants.UI.Armadillo]
)
hymnNumberInput.attributedPlaceholder = placeholder
hymnNumberInput.textColor = Constants.UI.Armadillo
hymnNumberInput.keyboardAppearance = .light
hymnNumberInput.delegate = self
directoryButton.backgroundColor = .white
directoryButton.setTitleColor(Constants.UI.Armadillo, for: .normal)
scheduleButton.backgroundColor = .white
scheduleButton.setTitleColor(Constants.UI.Armadillo, for: .normal)
}
private func alertUserOfFailure( message: String) {
DispatchQueue.main.async {
let alertController = UIAlertController(
title: "Action Failed",
message: message,
preferredStyle: UIAlertController.Style.alert
)
alertController.addAction(UIAlertAction(
title: "Dismiss",
style: UIAlertAction.Style.default,
handler: nil
))
self.present(alertController, animated: true, completion: nil)
}
}
func doneButtonAction() {
hymnNumberInput.resignFirstResponder()
if let hymnNumber : Int = Int(hymnNumberInput.text!) {
loadHymn(hymnNumber)
}
}
private func loadHymn(_ id: Int) {
impactGenerator = UIImpactFeedbackGenerator(style: .medium)
impactGenerator?.prepare()
let hymnVC = storyboard!.instantiateViewController(
withIdentifier: "HymnViewController"
) as! HymnViewController
hymnVC.number = id
impactGenerator?.impactOccurred()
present(hymnVC, animated: true, completion: nil)
impactGenerator = nil
}
private func loadDirectory() {
impactGenerator = UIImpactFeedbackGenerator(style: .medium)
impactGenerator?.prepare()
let directoryVC = storyboard!.instantiateViewController(
withIdentifier: "DirectoryListNavigationController"
)
impactGenerator?.impactOccurred()
present(directoryVC, animated: true, completion: nil)
impactGenerator = nil
}
private func loadSchedule() {
impactGenerator = UIImpactFeedbackGenerator(style: .medium)
impactGenerator?.prepare()
let scheduleVC = storyboard!.instantiateViewController(
withIdentifier: "ScheduleListNavigationController"
)
impactGenerator?.impactOccurred()
present(scheduleVC, animated: true, completion: nil)
impactGenerator = nil
}
}
// MARK: - HomeViewController: UITextFieldDelegate
extension HomeViewController: UITextFieldDelegate {
// MARK: Actions
@IBAction func userTappedView(_ sender: AnyObject) {
resignIfFirstResponder(hymnNumberInput)
doneButtonAction()
}
// MARK: UITextFieldDelegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
doneButtonAction()
return true
}
// Limit text field input to numbers in range
func textField(
_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String
) -> Bool {
selectionGenerator = UISelectionFeedbackGenerator()
selectionGenerator?.prepare()
guard let text = textField.text else {
selectionGenerator = nil
return true
}
let prospectiveText = (text as NSString).replacingCharacters(in: range, with: string)
if prospectiveText == "" {
selectionGenerator?.selectionChanged()
selectionGenerator = nil
return true
} else if let number = Int(prospectiveText), let hymnal = Hymnal.hymnal {
if number <= hymnal.hymns.count && number > 0 {
selectionGenerator?.selectionChanged()
selectionGenerator = nil
return true
}
}
selectionGenerator = nil
return false
}
// MARK: Show/Hide Keyboard
private func resignIfFirstResponder(_ textField: UITextField) {
if textField.isFirstResponder {
textField.resignFirstResponder()
}
}
}
| mit | 1c7e5b7e65e824e4414b278e5b696cfe | 31.805556 | 125 | 0.590707 | 5.362089 | false | false | false | false |
amolloy/LinkAgainstTheWorld | Frameworks/TileMap/TileMap/TlleMapSKRenderer.swift | 2 | 5277 | //
// TlleMapSKRenderer.swift
// TileMap
//
// Created by Andrew Molloy on 8/13/15.
// Copyright © 2015 Andrew Molloy. All rights reserved.
//
import Foundation
import SpriteKit
public class TileMapSKRenderer
{
let tileMap : TileMap
var textureAtlas : SKTextureAtlas?
enum Error : ErrorType
{
case MissingTileMapHeader
case MissingBlockGraphics
case MissingBlockData
case MissingColorMap
case InvalidBlockImage
case UnsupportedColorDepth
case CannotCreateDataProvider
case CannotCreateImageFromData
case MissingTextureAtlas
}
public init(tileMap: TileMap)
{
self.tileMap = tileMap
textureAtlas = nil
}
func createTextureAtlas() throws
{
guard let mapHeader = tileMap.mapHeader else
{
throw Error.MissingTileMapHeader
}
guard let buffer = tileMap.blockGraphics?.buffer else
{
throw Error.MissingBlockGraphics
}
let blockWidth = Int(mapHeader.blockSize.width)
let blockHeight = Int(mapHeader.blockSize.height)
let blockDepth = mapHeader.blockColorDepth
let bytesPerPixel = (blockDepth + 1) / 8
let blockDataSize = blockWidth * blockHeight * bytesPerPixel
let blockCount = buffer.count / blockDataSize
let cs = CGColorSpaceCreateDeviceRGB()!
var atlasInfo = [String: AnyObject]()
for i in 0..<blockCount
{
let offset = i * blockDataSize
let subBuffer = buffer[offset..<(offset + blockDataSize)]
let cgImage : CGImageRef
if mapHeader.blockColorDepth == 8
{
guard let colorMap = tileMap.colorMap else
{
throw Error.MissingColorMap
}
cgImage = try create8BitTexture(mapHeader.blockSize,
colorSpace: cs,
buffer: subBuffer,
colorMap: colorMap,
keyColor: mapHeader.keyColor8Bit)
}
else if mapHeader.blockColorDepth == 15 || mapHeader.blockColorDepth == 16
{
// TODO
throw Error.UnsupportedColorDepth
}
else if mapHeader.blockColorDepth == 24
{
cgImage = try create24BitTexture(mapHeader.blockSize,
colorSpace:cs,
buffer: subBuffer,
keyColor: mapHeader.keyColor)
}
else if mapHeader.blockColorDepth == 32
{
// TODO
throw Error.UnsupportedColorDepth
}
else
{
throw Error.UnsupportedColorDepth
}
atlasInfo[String(i)] = NSImage(CGImage: cgImage, size: NSSize(mapHeader.blockSize))
}
textureAtlas = SKTextureAtlas(dictionary: atlasInfo)
}
func create8BitTexture(blockSize: MapHeader.Size,
colorSpace: CGColorSpaceRef,
buffer: ArraySlice<UInt8>,
colorMap: ColorMap,
keyColor: UInt8) throws -> CGImageRef
{
var rgbBuffer = [UInt8]()
rgbBuffer.reserveCapacity(buffer.count * 4)
for key in buffer
{
if keyColor == key
{
rgbBuffer.append(0);
rgbBuffer.append(0);
rgbBuffer.append(0);
rgbBuffer.append(0);
}
else
{
let (r, g, b) = colorMap.palette[Int(key)]
rgbBuffer.append(r);
rgbBuffer.append(g);
rgbBuffer.append(b);
rgbBuffer.append(0xFF);
}
}
let rgbData = NSData(bytes: &rgbBuffer, length: rgbBuffer.count)
guard let provider = CGDataProviderCreateWithCFData(rgbData) else
{
throw Error.CannotCreateDataProvider
}
guard let cgImage = CGImageCreate(blockSize.width,
blockSize.height,
8,
32,
blockSize.width * 4,
colorSpace,
CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue),
provider,
nil,
true,
CGColorRenderingIntent.RenderingIntentDefault) else
{
throw Error.InvalidBlockImage
}
return cgImage
}
func create24BitTexture(blockSize: MapHeader.Size,
colorSpace: CGColorSpaceRef,
buffer: ArraySlice<UInt8>,
keyColor: TileMap.Color) throws -> CGImageRef
{
assert(buffer.count % 3 == 0)
var rgbBuffer = [UInt8]()
rgbBuffer.reserveCapacity((buffer.count / 3) * 4)
for i in 0..<(buffer.count / 3)
{
let r = buffer[i * 3 + 0]
let g = buffer[i * 3 + 1]
let b = buffer[i * 3 + 2]
let color : TileMap.Color = TileMap.Color(r: r, g: g, b: b)
rgbBuffer.append(r)
rgbBuffer.append(g)
rgbBuffer.append(b)
if keyColor == color
{
rgbBuffer.append(0);
}
else
{
rgbBuffer.append(0xFF);
}
}
let rgbData = NSData(bytes: &rgbBuffer, length: rgbBuffer.count)
guard let provider = CGDataProviderCreateWithCFData(rgbData) else
{
throw Error.CannotCreateDataProvider
}
guard let cgImage = CGImageCreate(blockSize.width,
blockSize.height,
8,
32,
blockSize.width * 4,
colorSpace,
CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue),
provider,
nil,
true,
CGColorRenderingIntent.RenderingIntentDefault) else
{
throw Error.InvalidBlockImage
}
return cgImage
}
public func node() throws -> TileMapSKNode?
{
if self.textureAtlas == nil
{
do
{
try createTextureAtlas()
}
catch let e
{
assertionFailure("Couldn't create texture atlas: \(e)")
return nil
}
}
guard let textureAtlas = self.textureAtlas else
{
throw Error.MissingTextureAtlas
}
let node = TileMapSKNode(tileMap: tileMap, textureAtlas: textureAtlas)
// TODO this api is all wrong.
var i = 0
for layer in tileMap.layers
{
let sn = node.buildTilesForLayer(layer)
if let sn = sn
{
sn.zPosition = CGFloat(i * 100)
node.addChild(sn)
}
++i
}
return node
}
}
| mit | 0c5f20ebc2164b9fca0c0d9015b5c208 | 20.534694 | 86 | 0.691433 | 3.339241 | false | false | false | false |
avario/ChainKit | ChainKit/ChainKit/UIToolbar + Chainkit.swift | 1 | 739 | //
// UIToolbar.swift
// ChainKit
//
// Created by Avario.
//
import UIKit
public extension UIToolbar {
public func barStyle(_ barStyle: UIBarStyle) -> Self {
self.barStyle = barStyle
return self
}
public func items(_ items: [UIBarButtonItem]?) -> Self {
self.items = items
return self
}
public func isTranslucent(_ isTranslucent: Bool) -> Self {
self.isTranslucent = isTranslucent
return self
}
public func barTintColor(_ barTintColor: UIColor?) -> Self {
self.barTintColor = barTintColor
return self
}
public func delegate(_ delegate: UIToolbarDelegate?) -> Self {
self.delegate = delegate
return self
}
}
| mit | 9b5ba6323f17c6fafb4b11e332813cf3 | 18.972973 | 66 | 0.607578 | 4.737179 | false | false | false | false |
IGRSoft/IGRPhotoTweaks | IGRPhotoTweaks/IGRPhotoTweakViewController+PHPhotoLibrary.swift | 1 | 2786 | //
// IGRPhotoTweakViewController+PHPhotoLibrary.swift
// Pods
//
// Created by Vitalii Parovishnyk on 4/26/17.
//
//
import Foundation
import Photos
extension IGRPhotoTweakViewController {
internal func saveToLibrary(image: UIImage) {
let writePhotoToLibraryBlock: (() -> Void)? = {
UIImageWriteToSavedPhotosAlbum(image, self, #selector(self.image(image:didFinishSavingWithError:contextInfo:)), nil)
}
if PHPhotoLibrary.authorizationStatus() == PHAuthorizationStatus.authorized {
writePhotoToLibraryBlock!()
}
else {
PHPhotoLibrary.requestAuthorization({ (status: PHAuthorizationStatus) in
if status == PHAuthorizationStatus.authorized {
DispatchQueue.main.async{
writePhotoToLibraryBlock!()
}
}
else {
DispatchQueue.main.async{
let ac = UIAlertController(title: "Authorization error",
message: "App don't granted to access to Photo Library",
preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
ac.addAction(UIAlertAction(title: "Settings", style: .default, handler: { (action) in
guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
return
}
if UIApplication.shared.canOpenURL(settingsUrl) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(settingsUrl)
} else {
UIApplication.shared.openURL(settingsUrl)
}
}
}))
self.present(ac, animated: true, completion: nil)
}
}
})
}
}
@objc func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafeRawPointer) {
if error != nil {
let ac = UIAlertController(title: "Save error",
message: error?.localizedDescription,
preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK",
style: .default,
handler: nil))
present(ac, animated: true, completion: nil)
}
}
}
| mit | d5c8e24349287cdbf4f0d6462b605dde | 41.212121 | 128 | 0.474874 | 6.331818 | false | false | false | false |
S7Vyto/SVCalendar | SVCalendar/SVCalendar/Calendar/Services/SVCalendarService.swift | 1 | 15082 | //
// SVCalendarService.swift
// SVCalendarView
//
// Created by Semyon Vyatkin on 18/10/2016.
// Copyright © 2016 Semyon Vyatkin. All rights reserved.
//
import Foundation
/**
Calendar Brain
This class contains all logic which will creates calendar with different dimensions (e.g. day, week, month, quarter and year)
*/
public struct SVCalendarDateFormat {
static let short = "dd.MM.yyyy"
static let full = "dd EEEE, MMMM yyyy"
static let monthYear = "MMMM yyyy"
static let dayMonthYear = "d MMM yyyy"
static let time = "HH:mm"
}
class SVCalendarService {
fileprivate let components: Set<Calendar.Component> = [
.second, .minute, .hour, .day, .weekday, .weekOfMonth, .month, .quarter, .year
]
enum SVCalendarWeekDays: Int {
case mon = 2
case tue = 3
case wed = 4
case thu = 5
case fri = 6
case sat = 7
case sun = 1
}
fileprivate let types: [SVCalendarType]
fileprivate let minYear: Int
fileprivate let maxYear: Int
fileprivate lazy var calendar: Calendar = {
var calendar = Calendar(identifier: Calendar.Identifier.gregorian)
calendar.locale = Locale.current
calendar.timeZone = TimeZone(secondsFromGMT: 0)!
calendar.firstWeekday = SVCalendarWeekDays.mon.rawValue
calendar.minimumDaysInFirstWeek = 7
return calendar
}()
fileprivate var currentDate: Date {
return calendar.date(from: currentComponents)!
}
fileprivate var currentComponents: DateComponents {
return calendar.dateComponents(components, from: Date())
}
fileprivate var visibleDate: Date!
fileprivate var calendarDates = [SVCalendarType : Array<[SVCalendarDate]>]()
fileprivate var calendarTitles = [SVCalendarType : [String]]()
var updatedDate: Date {
return self.visibleDate
}
// MARK: - Calendar Brain LifeCycle
init(types: [SVCalendarType], minYear: Int, maxYear: Int) {
self.types = types
self.minYear = minYear
self.maxYear = maxYear
self.visibleDate = currentDate
self.configurate()
}
deinit {
removeAllDates()
}
// MARK: - Calendar Methods
func configurate() {
self.removeAllDates()
self.updateCalendarDates()
self.updateCaledarTitles()
}
fileprivate func updateCalendarDates() {
if self.types.contains(SVCalendarType.all) {
self.calendarDates[.month] = self.configMonthDates()
self.calendarDates[.week] = self.configWeekDates()
self.calendarDates[.day] = self.configDayDates(nil)
return
}
if self.types.contains(SVCalendarType.month) {
self.calendarDates[.month] = self.configMonthDates()
}
if self.types.contains(SVCalendarType.week) {
self.calendarDates[.week] = self.configWeekDates()
}
if self.types.contains(SVCalendarType.day) {
self.calendarDates[.day] = self.configDayDates(nil)
}
}
func updateCaledarTitles() {
if self.types.contains(SVCalendarType.all) {
self.calendarTitles[.month] = self.calendar.shortWeekdaySymbols
self.calendarTitles[.week] = self.calendar.shortWeekdaySymbols
self.calendarTitles[.day] = self.calendar.shortWeekdaySymbols
return
}
if self.types.contains(SVCalendarType.month) {
self.calendarTitles[.month] = self.calendar.shortWeekdaySymbols
}
if self.types.contains(SVCalendarType.week) {
self.calendarTitles[.week] = self.calendar.shortWeekdaySymbols
}
if self.types.contains(SVCalendarType.day) {
self.calendarTitles[.day] = self.calendar.shortWeekdaySymbols
}
}
func updateDate(for calendarType: SVCalendarType, isDateIncrease: Bool) {
var dateComponents = self.calendar.dateComponents(self.components, from: self.visibleDate)
dateComponents.hour = 0
dateComponents.minute = 0
dateComponents.second = 0
let sign = isDateIncrease ? 1 : -1
switch calendarType {
case SVCalendarType.day: dateComponents.day! += sign
case SVCalendarType.week: dateComponents.day! += sign * 7
case SVCalendarType.month: dateComponents.month! += sign
default:
break
}
self.visibleDate = calendar.date(from: dateComponents)!
self.removeAllDates()
self.updateCalendarDates()
self.updateCaledarTitles()
}
func dates(for type: SVCalendarType) -> Array<[SVCalendarDate]> {
guard let dates = self.calendarDates[type] else {
return []
}
return dates
}
func titles(for type: SVCalendarType) -> [String] {
guard let titles = self.calendarTitles[type] else {
return []
}
return titles
}
func dateComponents(from date: Date) -> DateComponents {
return calendar.dateComponents(components, from: date)
}
fileprivate func removeAllDates() {
self.calendarDates.removeAll()
self.calendarTitles.removeAll()
}
// MARK: - Months Dates
fileprivate func monthBeginDate(from date: Date) -> Date {
let sourceComponents = calendar.dateComponents(components, from: date)
var dateComponents = DateComponents()
dateComponents.year = sourceComponents.year
dateComponents.month = sourceComponents.month
dateComponents.weekday = calendar.firstWeekday
dateComponents.day = 1
return calendar.date(from: dateComponents)!
}
fileprivate func monthEndDate(from date: Date) -> Date {
var sourceComponents = calendar.dateComponents(components, from: date)
let daysInMonth = calendar.range(of: .day, in: .month, for: date)
sourceComponents.day = daysInMonth!.count
return calendar.date(from: sourceComponents)!
}
fileprivate func configMonthDates() -> Array<[SVCalendarDate]> {
let beginMonthDate = monthBeginDate(from: visibleDate)
let endMonthDate = monthEndDate(from: beginMonthDate)
let daysInWeek = 7
let weeksInMonth = calendar.range(of: .weekOfMonth, in: .month, for: beginMonthDate)
let beginMonthComponents = calendar.dateComponents(components, from: beginMonthDate)
var endMonthComponents = calendar.dateComponents(components, from: endMonthDate)
var startDate: Date?
var endDate: Date?
if let weekDay = beginMonthComponents.weekday, indexOfDay(with: weekDay) <= daysInWeek {
startDate = calendar.date(byAdding: .day, value: -indexOfDay(with: weekDay), to: beginMonthDate)
}
else {
startDate = beginMonthDate
}
if let weekDay = endMonthComponents.weekday, indexOfDay(with: weekDay) != daysInWeek {
let difference = daysInWeek - indexOfDay(with: weekDay)
endDate = calendar.date(byAdding: .day, value: difference, to: endMonthDate)
}
else {
endDate = endMonthDate
}
if weeksInMonth!.count < 6 {
endDate = calendar.date(byAdding: .day, value: daysInWeek, to: endMonthDate)
endMonthComponents = calendar.dateComponents(components, from: endDate!)
if let weekDay = endMonthComponents.weekday, indexOfDay(with: weekDay) != daysInWeek {
let difference = daysInWeek - indexOfDay(with: weekDay)
endDate = calendar.date(byAdding: .day, value: difference, to: endDate!)
}
}
guard startDate != nil && endDate != nil else {
assert(false, " --- SVCalendarService - ConfigMonthDates - Month list is empty")
return []
}
var dates = [SVCalendarDate]()
while startDate!.compare(endDate!) != .orderedSame {
var calendarComponents = calendar.dateComponents(components, from: startDate!)
let title = "\(calendarComponents.day!)"
let isEnabled = (startDate?.compare(beginMonthDate) == .orderedDescending || startDate?.compare(beginMonthDate) == .orderedSame) && (startDate?.compare(endMonthDate) == .orderedAscending || startDate?.compare(endMonthDate) == .orderedSame)
let isCurrent = calendarComponents.day! == currentComponents.day!
let isWeekend = calendarComponents.weekday! == SVCalendarWeekDays.sat.rawValue || calendarComponents.weekday! == SVCalendarWeekDays.sun.rawValue
dates.append(SVCalendarDate(isEnabled: isEnabled,
isCurrent: isCurrent,
isWeekend: isWeekend,
title: title,
value: startDate!,
type: .month))
calendarComponents.day! += 1
startDate = calendar.date(from: calendarComponents)
}
return [dates]
}
// MARK: - Week Dates
fileprivate func weekDateComponents(from date: Date) -> DateComponents {
var dateComponents = calendar.dateComponents(components, from: date)
dateComponents.hour = 0
dateComponents.minute = 0
dateComponents.second = 0
return dateComponents
}
fileprivate func configWeekDates() -> Array<[SVCalendarDate]> {
let dateComponents = weekDateComponents(from: visibleDate)
let daysInWeek = 7
let beginMonthDate = monthBeginDate(from: visibleDate)
let endMonthDate = monthEndDate(from: beginMonthDate)
var beginWeekDate: Date?
var endWeekDate: Date?
if dateComponents.weekday! != SVCalendarWeekDays.mon.rawValue {
beginWeekDate = calendar.date(byAdding: .day, value: -indexOfDay(with: dateComponents.weekday!), to: calendar.date(from: dateComponents)!)
}
else {
beginWeekDate = visibleDate
}
endWeekDate = calendar.date(byAdding: .day, value: daysInWeek, to: beginWeekDate!)
guard beginWeekDate != nil && endWeekDate != nil else {
assert(false, " --- SVCalendarService - ConfigWeekDates - Week list is empty")
return []
}
var weekDates = [[SVCalendarDate]]()
while beginWeekDate!.compare(endWeekDate!) != .orderedSame {
var calendarComponents = calendar.dateComponents(components, from: beginWeekDate!)
let isEnabled = (beginWeekDate?.compare(beginMonthDate) == .orderedDescending || beginWeekDate?.compare(beginMonthDate) == .orderedSame) && (beginWeekDate?.compare(endMonthDate) == .orderedAscending || beginWeekDate?.compare(endMonthDate) == .orderedSame)
let isCurrent = calendarComponents.day! == currentComponents.day!
let isWeekend = calendarComponents.weekday! == SVCalendarWeekDays.sat.rawValue || calendarComponents.weekday! == SVCalendarWeekDays.sun.rawValue
if let dayDates = self.configDayDates(beginWeekDate).first {
for (index, value) in dayDates.enumerated() {
let date = SVCalendarDate(isEnabled: isEnabled,
isCurrent: isCurrent,
isWeekend: isWeekend,
title: value.title,
value: value.value,
type: .week)
if index > weekDates.count - 1 {
weekDates.append([date])
}
else {
weekDates[index].append(date)
}
}
}
calendarComponents.day! += 1
beginWeekDate = calendar.date(from: calendarComponents)
}
return weekDates
}
// MARK: - Day Dates
fileprivate func indexOfDay(with day: Int) -> Int {
switch day {
case SVCalendarWeekDays.mon.rawValue:
return 0
case SVCalendarWeekDays.tue.rawValue:
return 1
case SVCalendarWeekDays.wed.rawValue:
return 2
case SVCalendarWeekDays.thu.rawValue:
return 3
case SVCalendarWeekDays.fri.rawValue:
return 4
case SVCalendarWeekDays.sat.rawValue:
return 5
case SVCalendarWeekDays.sun.rawValue:
return 6
default:
return 0
}
}
fileprivate func endDayDate(from date: Date) -> Date {
var dateComponents = calendar.dateComponents(components, from: date)
dateComponents.weekday = calendar.firstWeekday
dateComponents.day! += 1
dateComponents.hour = 0
dateComponents.minute = 0
dateComponents.second = 0
return calendar.date(from: dateComponents)!
}
fileprivate func configDayDates(_ sourceDate: Date?) -> Array<[SVCalendarDate]> {
var beginDayDate = self.calendar.startOfDay(for: sourceDate ?? self.visibleDate)
let endDayDate = self.endDayDate(from: beginDayDate)
var dates = [SVCalendarDate]()
while beginDayDate.compare(endDayDate) != .orderedDescending {
var calendarComponents = self.calendar.dateComponents(components, from: beginDayDate)
let title = "\(calendarComponents.hour!)"
let isEnabled = calendarComponents.hour! >= currentComponents.hour! || calendarComponents.day! > currentComponents.day!
let isCurrent = calendarComponents.hour! == currentComponents.hour!
let isWeekend = calendarComponents.weekday! == SVCalendarWeekDays.sat.rawValue || calendarComponents.weekday! == SVCalendarWeekDays.sun.rawValue
dates.append(SVCalendarDate(isEnabled: isEnabled,
isCurrent: isCurrent,
isWeekend: isWeekend,
title: title,
value: beginDayDate,
type: .day))
calendarComponents.hour! += 1
beginDayDate = self.calendar.date(from: calendarComponents)!
}
return [dates]
}
}
| apache-2.0 | 473eb9b696926952749832354a7b9416 | 36.89196 | 267 | 0.584974 | 5.170038 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor | TranslationEditor/SelectAvatarVC.swift | 1 | 12065 | //
// SelectAvatarVC.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 21.2.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import UIKit
// This view controller handles avatar selection and authorization
class SelectAvatarVC: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, LiveQueryListener, StackDismissable
{
// TYPES -------------------
typealias QueryTarget = AvatarView
// OUTLETS -------------------
@IBOutlet weak var avatarCollectionView: UICollectionView!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var loginButton: BasicButton!
@IBOutlet weak var passwordView: KeyboardReactiveView!
@IBOutlet weak var errorLabel: UILabel!
@IBOutlet weak var topBar: TopBarUIView!
@IBOutlet weak var avatarsStackView: StatefulStackView!
// ATTRIBUTES ---------------
private var queryManager: LiveQueryManager<QueryTarget>?
private var avatarData = [(Avatar, AvatarInfo)]()
private var selectedData: (Avatar, AvatarInfo)?
private var usesSharedAccount = true
// COMPUTED PROPERTIES -------
var shouldDismissBelow: Bool { return !usesSharedAccount }
// LOAD -----------------------
override func viewDidLoad()
{
super.viewDidLoad()
topBar.configure(hostVC: self, title: "Select User")
avatarsStackView.register(avatarCollectionView, for: .data)
avatarsStackView.setState(.loading)
guard let projectId = Session.instance.projectId else
{
print("ERROR: No selected project -> No available avatar data")
avatarsStackView.errorOccurred()
return
}
guard let accountId = Session.instance.accountId else
{
print("ERROR: No account information available.")
avatarsStackView.errorOccurred()
return
}
// If logged in with a non-shared account, uses the only avatar for the project
// Otherwises reads all avatar data and filters out the non-shared later
do
{
if let project = try Project.get(projectId)
{
usesSharedAccount = project.sharedAccountId == accountId
if usesSharedAccount
{
queryManager = AvatarView.instance.avatarQuery(projectId: projectId).liveQueryManager
}
else
{
queryManager = AvatarView.instance.avatarQuery(projectId: projectId, accountId: accountId).liveQueryManager
}
}
}
catch
{
print("ERROR: Failed to read associated database data. \(error)")
}
avatarCollectionView.delegate = self
avatarCollectionView.dataSource = self
queryManager?.addListener(AnyLiveQueryListener(self))
passwordView.configure(mainView: view, elements: [loginButton, errorLabel, passwordField])
}
override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
hidePasswordView()
topBar.updateUserView()
// If the project has not been chosen, doesn't configure anything
if Session.instance.projectId != nil
{
// Sets up the top bar
let title = "Select User"
if let presentingViewController = presentingViewController
{
if let presentingViewController = presentingViewController as? SelectProjectVC
{
topBar.configure(hostVC: self, title: title, leftButtonText: presentingViewController.shouldDismissBelow ? "Log Out" : "Switch Project")
{
Session.instance.projectId = nil
presentingViewController.dismissFromAbove()
}
}
else
{
topBar.configure(hostVC: self, title: title, leftButtonText: "Back", leftButtonAction: { self.dismiss(animated: true, completion: nil) })
}
}
// If the avatar has already been chosen, skips this phase
// (The avatar must be enabled, however)
if let avatarId = Session.instance.avatarId
{
do
{
if let avatar = try Avatar.get(avatarId), !avatar.isDisabled
{
print("STATUS: Avatar already selected")
proceed(animated: false)
return
}
else
{
Session.instance.bookId = nil
Session.instance.avatarId = nil
}
}
catch
{
print("ERROR: Failed to read avatar data. \(error)")
}
}
// Otherwise starts the queries
queryManager?.start()
passwordView.startKeyboardListening()
}
}
override func viewDidDisappear(_ animated: Bool)
{
passwordView.endKeyboardListening()
// Doen't need to continue with live queries while the view is not visible
queryManager?.stop()
}
// ACTIONS -------------------
@IBAction func passwordFieldChanged(_ sender: Any)
{
// Enables or disables login button
loginButton.isEnabled = passwordField.text.exists { !$0.isEmpty } || selectedData.exists { !$0.1.requiresPassword }
}
@IBAction func cancelPressed(_ sender: Any)
{
// Hide password area. Resets selection
hidePasswordView()
}
@IBAction func loginPressed(_ sender: Any)
{
guard let (selectedAvatar, selectedInfo) = selectedData else
{
print("ERROR: No selected avatar")
return
}
// Checks password, moves to next view
guard (passwordField.text.exists { selectedInfo.authenticate(loggedAccountId: Session.instance.accountId, password: $0) }) else
{
errorLabel.isHidden = false
return
}
Session.instance.avatarId = selectedAvatar.idString
proceed()
}
// IMPLEMENTED METHODS -------
func rowsUpdated(rows: [Row<QueryTarget>])
{
do
{
// If using a shared account, presents all viable options in the collection view
if usesSharedAccount
{
avatarData = try rows.map { try $0.object() }.compactMap
{
avatar in
if !avatar.isDisabled, let info = try avatar.info(), info.isShared
{
return (avatar, info)
}
else
{
return nil
}
}
avatarsStackView.dataLoaded()
avatarCollectionView.reloadData()
}
// Otherwise just finds the first applicable avatar and uses that
else
{
if let avatar = try rows.first?.object()
{
// If the user's avatar was disabled for some reason, enables it
if avatar.isDisabled
{
avatar.isDisabled = false
try avatar.push()
}
print("STATUS: Proceeding with non-shared account avatar")
Session.instance.avatarId = avatar.idString
proceed()
}
else
{
do
{
if let accountId = Session.instance.accountId, let account = try AgricolaAccount.get(accountId)
{
avatarsStackView.dataLoaded()
createAvatar(withName: account.username)
}
else
{
print("ERROR: No account data available")
avatarsStackView.errorOccurred(title: "Can't create a new user", description: "Account data was not found")
return
}
}
catch
{
print("ERROR: Failed to read account data. \(error)")
avatarsStackView.errorOccurred(title: "Can't create a new user", canContinueWithData: false)
}
}
}
}
catch
{
print("ERROR: Failed to process avatar data. \(error)")
avatarsStackView.errorOccurred()
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
{
return avatarData.count + 1
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell
{
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: AvatarCell.identifier, for: indexPath) as! AvatarCell
// The last row is used for the avatar addition
if indexPath.row == avatarData.count
{
cell.configure(avatarName: "New User", avatarImage: #imageLiteral(resourceName: "addIcon"))
}
else
{
let (avatar, info) = avatarData[indexPath.row]
cell.configure(avatarName: avatar.name, avatarImage: info.image)
}
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
{
// Selects an avatar and displays the password view
if selectedData == nil
{
// If the last cell was selected, displays a view for adding a new avatar
if indexPath.row == avatarData.count
{
createAvatar()
}
else
{
selectedData = avatarData[indexPath.row]
if selectedData!.1.requiresPassword
{
errorLabel.isHidden = true
passwordView.isHidden = false
}
else
{
Session.instance.avatarId = selectedData!.0.idString
proceed()
}
}
}
}
func willDissmissBelow()
{
// Deselects the project
Session.instance.projectId = nil
}
// OTHER METHODS --------
func proceed(animated: Bool = true)
{
// Presents the main menu
let storyboard = UIStoryboard(name: "MainMenu", bundle: nil)
guard let controller = storyboard.instantiateInitialViewController() else
{
print("ERROR: Failed to instantiate VC for the main menu")
return
}
present(controller, animated: animated, completion: nil)
}
private func createAvatar(withName avatarName: String? = nil)
{
displayAlert(withIdentifier: "EditAvatar", storyBoardId: "MainMenu")
{
($0 as! EditAvatarVC).configureForCreate(avatarName: avatarName)
}
}
private func hidePasswordView()
{
// Hide password area. Resets selection
passwordField.text = nil
selectedData = nil
passwordView.isHidden = true
avatarCollectionView.selectItem(at: nil, animated: true, scrollPosition: .left)
}
}
| mit | 1313645ee40dce7c132cf3c8cd6a092d | 32.511111 | 157 | 0.523127 | 5.963421 | false | false | false | false |
coffee-cup/solis | SunriseSunset/TimeZones.swift | 1 | 3685 | //
// TimeZone.swift
// SunriseSunset
//
// Created by Jake Runzer on 2016-06-27.
// Copyright © 2016 Puddllee. All rights reserved.
//
import Foundation
import CoreLocation
import Alamofire
class TimeZones {
let ApiKey = "3GEZEJL3FJ03"
let Endpoint = "https://api.timezonedb.com/v2/get-time-zone"
static var currentTimeZone: TimeZone {
if SunLocation.isCurrentLocation() {
return TimeZone.ReferenceType.local
}
if let timeZone = getTimeZone() {
return timeZone
}
return TimeZone.ReferenceType.local
}
init() {
Bus.subscribeEvent(.fetchTimeZone, observer: self, selector: #selector(fetchTimeZone))
}
@objc func fetchTimeZone() {
if let location = SunLocation.getLocation() {
timeZoneForLocation(location) { gmtOffset, abbreviation in
guard let gmtOffset = gmtOffset else {
return
}
// print("gmt offset: \(gmtOffset)")
// print("abb: \(abbreviation)")
self.saveTimeZone(gmtOffset)
if !SunLocation.isCurrentLocation() {
if let placeID = SunLocation.getPlaceID() {
SunLocation.updateLocationHistoryWithTimeZone(location, placeID: placeID, timeZoneOffset: gmtOffset)
}
}
}
}
}
func saveTimeZone(_ gmtOffset: Int) {
Defaults.defaults.set(gmtOffset, forKey: DefaultKey.locationTimeZoneOffset.description)
Bus.sendMessage(.gotTimeZone, data: nil )
}
class func getTimeZone() -> TimeZone? {
let gmtOffset = Defaults.defaults.integer(forKey: DefaultKey.locationTimeZoneOffset.description)
let timeZone = TimeZone(secondsFromGMT: gmtOffset)
return timeZone
}
func timeZoneForLocation(_ location: CLLocationCoordinate2D, completionHandler: @escaping (_ gmtOffset: Int?, _ abbreviation: String?) -> ()) {
let requestString = "\(Endpoint)?by=position&format=json&key=\(ApiKey)&lat=\(location.latitude)&lng=\(location.longitude)"
AF.request(requestString)
.responseJSON { response in
// print(response.request) // original URL request
// print(response.response) // URL response
// print(response.data) // server data
// print(response.result) // result of response serialization
guard let data = response.data else {
print("Data from response is nil")
completionHandler(nil, nil)
return
}
let json = try! JSON(data: data)
guard let abbreviation = json["abbreviation"].string else {
print("Abbreviation from response is nil")
completionHandler(nil, nil)
return
}
guard let gmtOffset = json["gmtOffset"].int else {
print("GmtOffset from response is nil")
completionHandler(nil, nil)
return
}
// guard let dst = json["dst"].string else {
// print("DST from response is nil")
// completionHandler(nil, nil)
// return
// }
// let daylightSavings = dst == "1"
let offsetWithGmt = gmtOffset
// if daylightSavings {
// offsetWithGmt += 60 * 60
// }
completionHandler(offsetWithGmt, abbreviation)
}
}
}
| mit | b4adb40cc0c7d7b6ffcf906a44296639 | 33.429907 | 147 | 0.551846 | 4.912 | false | false | false | false |
danielmartin/swift | test/SILGen/generic_literals.swift | 2 | 4115 | // RUN: %target-swift-emit-silgen %s | %FileCheck %s
// CHECK-LABEL: sil hidden [ossa] @$s16generic_literals0A14IntegerLiteral1xyx_ts013ExpressibleBycD0RzlF : $@convention(thin) <T where T : ExpressibleByIntegerLiteral> (@in_guaranteed T) -> () {
func genericIntegerLiteral<T : ExpressibleByIntegerLiteral>(x: T) {
var x = x
// CHECK: [[ADDR:%.*]] = alloc_stack $T
// CHECK: [[TMETA:%.*]] = metatype $@thick T.Type
// CHECK: [[LITVAR:%.*]] = alloc_stack $T.IntegerLiteralType
// CHECK: [[LITMETA:%.*]] = metatype $@thick T.IntegerLiteralType.Type
// CHECK: [[INTLIT:%.*]] = integer_literal $Builtin.IntLiteral, 17
// CHECK: [[BUILTINCONV:%.*]] = witness_method $T.IntegerLiteralType, #_ExpressibleByBuiltinIntegerLiteral.init!allocator.1
// CHECK: [[LIT:%.*]] = apply [[BUILTINCONV]]<T.IntegerLiteralType>([[LITVAR]], [[INTLIT]], [[LITMETA]]) : $@convention(witness_method: _ExpressibleByBuiltinIntegerLiteral) <τ_0_0 where τ_0_0 : _ExpressibleByBuiltinIntegerLiteral> (Builtin.IntLiteral, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[TCONV:%.*]] = witness_method $T, #ExpressibleByIntegerLiteral.init!allocator.1
// CHECK: apply [[TCONV]]<T>([[ADDR]], [[LITVAR]], [[TMETA]]) : $@convention(witness_method: ExpressibleByIntegerLiteral) <τ_0_0 where τ_0_0 : ExpressibleByIntegerLiteral> (@in τ_0_0.IntegerLiteralType, @thick τ_0_0.Type) -> @out τ_0_0
x = 17
}
// CHECK-LABEL: sil hidden [ossa] @$s16generic_literals0A15FloatingLiteral1xyx_ts018ExpressibleByFloatD0RzlF : $@convention(thin) <T where T : ExpressibleByFloatLiteral> (@in_guaranteed T) -> () {
func genericFloatingLiteral<T : ExpressibleByFloatLiteral>(x: T) {
var x = x
// CHECK: [[TVAL:%.*]] = alloc_stack $T
// CHECK: [[TMETA:%.*]] = metatype $@thick T.Type
// CHECK: [[FLT_VAL:%.*]] = alloc_stack $T.FloatLiteralType
// CHECK: [[TFLT_META:%.*]] = metatype $@thick T.FloatLiteralType.Type
// CHECK: [[LIT_VALUE:%.*]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x4004000000000000|0x4000A000000000000000}}
// CHECK: [[BUILTIN_CONV:%.*]] = witness_method $T.FloatLiteralType, #_ExpressibleByBuiltinFloatLiteral.init!allocator.1
// CHECK: apply [[BUILTIN_CONV]]<T.FloatLiteralType>([[FLT_VAL]], [[LIT_VALUE]], [[TFLT_META]]) : $@convention(witness_method: _ExpressibleByBuiltinFloatLiteral) <τ_0_0 where τ_0_0 : _ExpressibleByBuiltinFloatLiteral> (Builtin.FPIEEE{{64|80}}, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[CONV:%.*]] = witness_method $T, #ExpressibleByFloatLiteral.init!allocator.1
// CHECK: apply [[CONV]]<T>([[TVAL]], [[FLT_VAL]], [[TMETA]]) : $@convention(witness_method: ExpressibleByFloatLiteral) <τ_0_0 where τ_0_0 : ExpressibleByFloatLiteral> (@in τ_0_0.FloatLiteralType, @thick τ_0_0.Type) -> @out τ_0_0
x = 2.5
}
// CHECK-LABEL: sil hidden [ossa] @$s16generic_literals0A13StringLiteral1xyx_ts013ExpressibleBycD0RzlF : $@convention(thin) <T where T : ExpressibleByStringLiteral> (@in_guaranteed T) -> () {
func genericStringLiteral<T : ExpressibleByStringLiteral>(x: T) {
var x = x
// CHECK: [[LIT_VALUE:%.*]] = string_literal utf8 "hello"
// CHECK: [[TSTR_META:%.*]] = metatype $@thick T.StringLiteralType.Type
// CHECK: [[STR_VAL:%.*]] = alloc_stack $T.StringLiteralType
// CHECK: [[BUILTIN_CONV:%.*]] = witness_method $T.StringLiteralType, #_ExpressibleByBuiltinStringLiteral.init!allocator.1
// CHECK: apply [[BUILTIN_CONV]]<T.StringLiteralType>([[STR_VAL]], [[LIT_VALUE]], {{.*}}, [[TSTR_META]]) : $@convention(witness_method: _ExpressibleByBuiltinStringLiteral) <τ_0_0 where τ_0_0 : _ExpressibleByBuiltinStringLiteral> (Builtin.RawPointer, Builtin.Word, Builtin.Int1, @thick τ_0_0.Type) -> @out τ_0_0
// CHECK: [[TMETA:%.*]] = metatype $@thick T.Type
// CHECK: [[TVAL:%.*]] = alloc_stack $T
// CHECK: [[CONV:%.*]] = witness_method $T, #ExpressibleByStringLiteral.init!allocator.1
// CHECK: apply [[CONV]]<T>([[TVAL]], [[STR_VAL]], [[TMETA]]) : $@convention(witness_method: ExpressibleByStringLiteral) <τ_0_0 where τ_0_0 : ExpressibleByStringLiteral> (@in τ_0_0.StringLiteralType, @thick τ_0_0.Type) -> @out τ_0_0
x = "hello"
}
| apache-2.0 | 2b8b02b27596d5032fcdf251f41c4578 | 80.76 | 312 | 0.681996 | 3.554783 | false | false | false | false |
johnoppenheimer/epiquote-ios | EpiquoteSwift/models/Quote.swift | 1 | 459 | //
// Quote.swift
// EpiquoteSwift
//
// Created by Maxime Cattet on 17/11/2016.
//
//
import UIKit
import IGListKit
class Quote: NSObject {
var author: String = ""
var context: String?
var content: String = ""
var date: Date = Date()
init(author: String, context: String?, content: String, date: Date) {
self.author = author
self.content = content
self.context = context
self.date = date
}
}
| mit | df4d03d23033e8be5358f81adc741523 | 18.125 | 73 | 0.59695 | 3.614173 | false | false | false | false |
johnoppenheimer/epiquote-ios | EpiquoteSwift/views/ContentCollectionViewCell.swift | 1 | 1305 | //
// ContentCollectionViewCell.swift
// EpiquoteSwift
//
// Created by Maxime Cattet on 17/11/2016.
//
//
import UIKit
class ContentCollectionViewCell: UICollectionViewCell {
lazy var textView: UITextView = {
let view = UITextView()
view.backgroundColor = .clear
view.isSelectable = false
view.isEditable = false
view.isScrollEnabled = false
view.font = UIFont.systemFont(ofSize: 14.0)
self.contentView.addSubview(view)
return view
}()
lazy var colorBlockView: UIView = {
let view = UIView()
self.contentView.addSubview(view)
return view
}()
override func layoutSubviews() {
super.layoutSubviews()
self.textView.autoPinEdge(toSuperviewEdge: .top, withInset: 5)
self.textView.autoPinEdge(toSuperviewEdge: .left, withInset: 10)
self.textView.autoPinEdge(toSuperviewEdge: .right, withInset: 10)
self.textView.autoPinEdge(toSuperviewEdge: .bottom, withInset: 5)
self.colorBlockView.autoPinEdge(toSuperviewEdge: .left)
self.colorBlockView.autoPinEdge(toSuperviewEdge: .top)
self.colorBlockView.autoPinEdge(toSuperviewEdge: .bottom)
self.colorBlockView.autoSetDimension(.width, toSize: 5)
}
}
| mit | 1741b813f9ecd0dde1ff888dc9af6dc7 | 30.071429 | 73 | 0.662069 | 4.677419 | false | false | false | false |
mightydeveloper/swift | validation-test/compiler_crashers_fixed/1858-llvm-densemap-swift-valuedecl.swift | 13 | 902 | // RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct d<T where g: A where g, f<T) -> T -> String {
let c {
class p == {
protocol f {
return self["
}
class k , b {
(Any, m.init(j, i l, b class B, AnyObject) -> T {
u m h: k<T> String {
}
}
}
func b> String = T> d<T where T: Int = [1
j : A> Any) + seq
struct C<T) -> {
}
func b() -> i<l y ed) -> {
f : A {
func f.m)
func a
typealias B == g.E
()-> {
}
protocol f d{ se
}
)
func d<T
return d.i : Array<T>)
}
protocol d = b.C<T.Type) -> U) -> Any) {
}
case .c(() -> t.f = g, o>>(b
func g<l p : ()
func a: b
}
return { enum a!)) -> {
enum A {
let n1: (p: P> T {
struct c(r: c, l lk: NSObject {
enum g : Array<h == [u, (n<h {
}
typealias e = [q(()
func f: (x: B) -> : c> (g.p, d<q ")))
}
o
| apache-2.0 | d0700952b7a65683dde8308eac686239 | 16.686275 | 87 | 0.553215 | 2.379947 | false | false | false | false |
edx/edx-app-ios | Source/UIView+LayoutDirection.swift | 1 | 1590 | //
// UIView+LayoutDirection.swift
// edX
//
// Created by Akiva Leffert on 7/20/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
extension UIView {
@objc var isRightToLeft : Bool {
let direction = UIView.userInterfaceLayoutDirection(for: self.semanticContentAttribute)
switch direction {
case .leftToRight: return false
case .rightToLeft: return true
@unknown default: return false
}
}
}
enum LocalizedHorizontalContentAlignment {
case Leading
case Center
case Trailing
case Fill
}
extension UIControl {
var localizedHorizontalContentAlignment : LocalizedHorizontalContentAlignment {
get {
switch self.contentHorizontalAlignment {
case .left:
return self.isRightToLeft ? .Trailing : .Leading
case .right:
return self.isRightToLeft ? .Leading : .Trailing
case .center:
return .Center
case .fill:
return .Fill
default:
return .Fill
}
}
set {
switch newValue {
case .Leading:
self.contentHorizontalAlignment = self.isRightToLeft ? .right : .left
case .Trailing:
self.contentHorizontalAlignment = self.isRightToLeft ? .left : .right
case .Center:
self.contentHorizontalAlignment = .center
case .Fill:
self.contentHorizontalAlignment = .fill
}
}
}
}
| apache-2.0 | 3eecf1ec6f67b4fb4058353680691574 | 26.413793 | 95 | 0.574843 | 5.445205 | false | false | false | false |
laurentmorvillier/Stax | Stax/Classes/MapView.swift | 1 | 1372 | //
// MapView.swift
// Stax
//
// Created by Lolo on 14/06/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import UIKit
import MapKit
class ImagePointAnnotation: MKPointAnnotation {
var imageName: String!
}
open class MapView : MKMapView {
open func addAnnotation(_ coordinates: CLLocationCoordinate2D, name: String) -> MKAnnotation {
let annotation: MKPointAnnotation = MKPointAnnotation()
annotation.coordinate = coordinates
annotation.title = name
self.addAnnotation(annotation)
return annotation
}
open func centerMap(_ coordinates: CLLocationCoordinate2D, span: MKCoordinateSpan) {
let viewregion: MKCoordinateRegion = MKCoordinateRegion(center: coordinates, span: span)
let adjustedRegion: MKCoordinateRegion = self.regionThatFits(viewregion)
self.setRegion(adjustedRegion, animated: true)
self.showsUserLocation = true
}
open func zoomMapBy(_ delta: Double) { // example: 0.5 to zoom in, 2 to zoom out
var region:MKCoordinateRegion = self.region
var span:MKCoordinateSpan = self.region.span
span.latitudeDelta *= delta;
span.longitudeDelta *= delta;
region.span = span;
self.setRegion(region, animated: true)
}
}
| mit | 4f5c0d3cff88d9eb3a08fc44c232afd9 | 26.979592 | 98 | 0.65062 | 4.967391 | false | false | false | false |
tylerbrockett/cse394-principles-of-mobile-applications | lab-6/lab-6/lab-6/NetworkAsyncTask.swift | 1 | 2561 | /*
* @author Tyler Brockett mailto:[email protected]
* @course ASU CSE 394
* @project Lab 6
* @version March 21, 2016
* @project-description Collects data from www.geonames.org and presents it to the user.
* @class-name NetworkAsyncTask.swift
* @class-description Performs REST call on separate thread so UI stays responsive.
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Tyler Brockett
*
* 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
import Foundation
class NetworkAsyncTask {
func sendHttpRequest(request: NSMutableURLRequest,
callback: (String, String?) -> Void) {
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
(data, response, error) -> Void in
if (error != nil) {
callback("", error!.localizedDescription)
} else {
dispatch_async(dispatch_get_main_queue(),
{callback(NSString(data: data!,
encoding: NSUTF8StringEncoding)! as String, nil)})
}
}
task.resume()
}
func getEarthquakes(queryURL:String, callback: (String, String?) -> Void) -> Bool {
var ret:Bool = false
do {
let request = NSMutableURLRequest(URL: NSURL(string: queryURL)!)
request.HTTPMethod = "GET"
sendHttpRequest(request, callback: callback)
ret = true
}
return ret
}
}
| mit | f28412dde0efa4e24089fd13d49679e1 | 39.650794 | 88 | 0.655994 | 4.548845 | false | false | false | false |
AlexanderNey/Futuristics | Tests/FutureTests.swift | 1 | 12492 | //
// FutureTests.swift
// Futuristics
//
// Created by Alexander Ney on 04/08/2015.
// Copyright © 2015 Alexander Ney. All rights reserved.
//
import Foundation
import XCTest
@testable import Futuristics
class FutureTests: XCTestCase {
enum TestError: Error {
case someError
case anotherError
}
func testFulfill() {
let future = Future<String>()
if case .pending = future.state {
} else {
XCTFail("initial state should be pending")
}
future.fulfill("test")
if case .fulfilled(let value) = future.state, value == "test" {
} else {
XCTFail("Future should be fulfilled with value 'test' but was \(future.state)")
}
}
func testReject() {
let future = Future<String>()
if case .pending = future.state {
} else {
XCTFail("initial state should be pending")
}
future.reject(TestError.anotherError)
if case .rejected(let error) = future.state, error as? TestError == TestError.anotherError {
} else {
XCTFail("Future should be rejected with error \(TestError.anotherError) but was \(future.state)")
}
}
func testMultipleFulfillmentRejectment() {
let fulfilledPromise = Future<String>()
fulfilledPromise.fulfill("test")
fulfilledPromise.fulfill("testA")
fulfilledPromise.reject(TestError.anotherError)
if case .fulfilled(let value) = fulfilledPromise.state, value == "test" {
} else {
XCTFail("Future should be fulfilled with value 'test' but was \(fulfilledPromise.state)")
}
let rejectedPromise = Future<String>()
rejectedPromise.reject(TestError.someError)
rejectedPromise.fulfill("test")
if case .rejected(let error) = rejectedPromise.state, error as? TestError == TestError.someError {
} else {
XCTFail("Future should be rejected with error \(TestError.someError) but was \(rejectedPromise.state)")
}
}
func testFulfillHandler() {
let future = Future<String>()
let handlerExpectation = expectation(description: "Success handler called")
future.onSuccess { value in
XCTAssertEqual(value, "test")
handlerExpectation.fulfill()
}
future.fulfill("test")
waitForExpectationsWithDefaultTimeout()
}
func testFulfillMultipleHandler() {
let future = Future<String>()
let successExpectation = expectation(description: "Success handler called")
let secondSuccessExpectation = expectation(description: "Second success handler called")
let afterFulfillSuccessExpectation = expectation(description: "After fulfillment success handler called")
let finallyExpectation = expectation(description: "Finally called")
let afterFulfillFinallyExpectation = expectation(description: "After fulfillment finally called")
future.onSuccess { value in
XCTAssertEqual(value, "test")
successExpectation.fulfill()
}.onFailure { _ in
XCTFail()
}.onSuccess { value in
XCTAssertEqual(value, "test")
secondSuccessExpectation.fulfill()
}.finally {
finallyExpectation.fulfill()
}
XCTAssertTrue(future.state.isPending)
future.fulfill("test")
XCTAssertFalse(future.state.isPending)
future.finally {
afterFulfillFinallyExpectation.fulfill()
}.onSuccess { value in
XCTAssertEqual(value, "test")
afterFulfillSuccessExpectation.fulfill()
}.onFailure { _ in
XCTFail()
}
waitForExpectationsWithDefaultTimeout()
}
func testRejectMultipleHandler() {
let future = Future<String>()
let failureExpectation = expectation(description: "Failure handler called")
let afterFulfillFailureExpectation = expectation(description: "After fulfillment failure handler called")
let finallyExpectation = expectation(description: "Finally called")
let afterFulfillFinallyExpectation = expectation(description: "After fulfillment finally called")
future.onSuccess { value in
XCTFail()
}.onFailure { _ in
failureExpectation.fulfill()
}.onSuccess { value in
XCTFail("second success block was not expected to be called")
}.finally {
finallyExpectation.fulfill()
}
XCTAssertTrue(future.state.isPending)
future.reject(TestError.someError)
XCTAssertFalse(future.state.isPending)
future.finally {
afterFulfillFinallyExpectation.fulfill()
}.onSuccess { value in
XCTFail()
}.onFailure { _ in
afterFulfillFailureExpectation.fulfill()
}
waitForExpectationsWithDefaultTimeout()
}
func testResolveRejectionWithThrowable() {
func willThrow() throws -> String {
throw TestError.someError
}
let future = Future<String>()
if case .pending = future.state {
} else {
XCTFail("initial state should be pending")
}
future.resolveWith { try willThrow() }
if case .rejected(let error) = future.state, error as? TestError == TestError.someError {
} else {
XCTFail("Future should be rejected with error \(TestError.anotherError) but was \(future.state)")
}
}
func testResolveFulfillWithThrowable() {
func willNotThrow() throws -> String {
return "test"
}
let future = Future<String>()
if case .pending = future.state {
} else {
XCTFail("initial state should be pending")
}
future.resolveWith { try willNotThrow() }
if case .fulfilled(let value) = future.state, value == "test" {
} else {
XCTFail("Future should be fulfilled with value 'test' but was \(future.state)")
}
}
func testSuccessDefaultContext() {
let future = Future<Void>()
let preFulfillExpectation = expectation(description: "Pre fulfill success should execute on background thread")
future.onSuccess {
if Thread.isMainThread {
preFulfillExpectation.fulfill()
} else {
let queueLabel = String(validatingUTF8: __dispatch_queue_get_label(nil))
XCTFail("wrong queue \(queueLabel)")
}
}
let dispatchTime = DispatchTime.now() + Double(Int64(0.3 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.global(qos: .userInteractive).asyncAfter(deadline: dispatchTime) {
future.fulfill()
}
waitForExpectationsWithDefaultTimeout()
let postFulfillExpectation = expectation(description: "Post fulfill success should execute on main thread")
future.onSuccess {
if Thread.isMainThread {
postFulfillExpectation.fulfill()
} else {
let queueLabel = String(validatingUTF8: __dispatch_queue_get_label(nil))
XCTFail("wrong queue \(queueLabel)")
}
}
waitForExpectationsWithDefaultTimeout()
}
func testSuccessCustomContext() {
let future = Future<Void>()
let preFulfillExpectation = expectation(description: "Pre fulfill success should execute on main thread")
future.onSuccess(on: DispatchQueue.main) {
if Thread.isMainThread {
preFulfillExpectation.fulfill()
}
}
let dispatchTime = DispatchTime.now() + Double(Int64(0.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.global(qos: .userInteractive).asyncAfter(deadline: dispatchTime) {
future.fulfill()
}
waitForExpectationsWithDefaultTimeout()
let postFulfillExpectation = expectation(description: "Post fulfill success should execute on background thread")
future.onSuccess(on: DispatchQueue.global(qos: .userInteractive)) {
if !Thread.isMainThread {
postFulfillExpectation.fulfill()
}
}
waitForExpectationsWithDefaultTimeout()
}
func testBurteforceAddCompletionBlocksOnMainQueueFulfillFutureOnCustomQueue() {
for _ in 1...100 {
let future = Future<Void>()
let preFulfillExpectation = expectation(description: "Bruteforce")
let dispatchQueue = DispatchQueue(label: "custom serial queue", attributes: [])
var successExecuted = 0
var finallyExecuted = 0
for i in 1...50 {
if i == 25 {
dispatchQueue.async {
future.fulfill()
}
}
future.onSuccess {
successExecuted += 1
if successExecuted == 50 && finallyExecuted == 50 {
preFulfillExpectation.fulfill()
}
}.finally {
finallyExecuted += 1
if successExecuted == 50 && finallyExecuted == 50 {
preFulfillExpectation.fulfill()
}
}
}
waitForExpectationsWithDefaultTimeout()
}
}
func testBurteforceAddCompletionBlocksOnMainQueueFulfillFutureOnMainQueue() {
for _ in 1...100 {
let future = Future<Void>()
let preFulfillExpectation = expectation(description: "Bruteforce")
var successExecuted = 0
var finallyExecuted = 0
for i in 1...50 {
if i == 25 {
DispatchQueue.main.async {
future.fulfill()
}
}
future.onSuccess {
successExecuted += 1
if successExecuted == 50 && finallyExecuted == 50 {
preFulfillExpectation.fulfill()
}
}.finally {
finallyExecuted += 1
if successExecuted == 50 && finallyExecuted == 50 {
preFulfillExpectation.fulfill()
}
}
}
waitForExpectationsWithDefaultTimeout()
}
}
func testBurteforceAddCompletionBlocksOnRandomCustomQueueFulfillFutureOnMainQueue() {
for _ in 1...100 {
let future = Future<Void>()
let preFulfillExpectation = expectation(description: "Bruteforce")
var successExecuted = 0
var finallyExecuted = 0
for i in 1...50 {
if i == 25 {
future.fulfill()
}
let dispatchQueue = DispatchQueue(label: "custom serial queue \(i)", attributes: [])
dispatchQueue.async {
future.onSuccess {
successExecuted += 1
if successExecuted == 50 && finallyExecuted == 50 {
preFulfillExpectation.fulfill()
}
}
}
_ = dispatchQueue.sync {
future.finally {
finallyExecuted += 1
if successExecuted == 50 && finallyExecuted == 50 {
preFulfillExpectation.fulfill()
}
}
}
}
waitForExpectationsWithDefaultTimeout()
}
}
}
| mit | 12e6e9a8cae5f820e69eb8f5813aa272 | 32.309333 | 121 | 0.538468 | 5.790913 | false | true | false | false |
coderMONSTER/iosstar | iOSStar/Scenes/Market/CustomView/MarketMenuView.swift | 1 | 8179 | //
// MarketMenuView.swift
// iOSStar
//
// Created by J-bb on 17/4/26.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
class MarketMenuView: UIView, UICollectionViewDelegate, UICollectionViewDataSource, UIScrollViewDelegate, MenuViewDelegate,SubViewItemSelectDelegate{
var delegate:SubViewItemSelectDelegate?
var items:[String]? {
didSet{
menuView?.items = items
subViewCollectionView?.reloadData()
}
}
var types:[MarketClassifyModel]? {
didSet {
let indexPath = IndexPath(item: 0, section: 0)
menuViewDidSelect(indexPath: indexPath)
menuView?.selected(index: 0)
}
}
var subViews:[UIView]?
var selectIndexPath:IndexPath = IndexPath(item: 0, section: 0)
lazy var infoView:UIView = {
let view = UIView()
view.backgroundColor = UIColor(hexString: "FAFAFA")
return view
}()
lazy var allLabel: UILabel = {
let label = UILabel()
label.text = "全部"
label.textColor = UIColor(hexString: "333333")
label.font = UIFont.systemFont(ofSize: 14)
return label
}()
lazy var priceTypeButton: UILabel = {
let label = UILabel()
label.setAttributeText(text: "最近价 元/秒", firstFont: 14.0, secondFont: 12.0, firstColor: UIColor(hexString: "333333"), secondColor: UIColor(hexString: "333333"), range: NSRange(location: 4, length: 3))
return label
}()
lazy var priceChangeButton: UIButton = {
let button = UIButton(type: .custom)
button.setTitle("涨跌幅", for: .normal)
button.titleLabel?.font = UIFont.systemFont(ofSize: 14)
button.setTitleColor(UIColor(hexString: "333333"), for: .normal)
return button
}()
lazy var priceImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "market_price"))
return imageView
}()
lazy var changeImageView: UIImageView = {
let imageView = UIImageView(image: UIImage(named: "marketlist_down"))
imageView.isUserInteractionEnabled = true
return imageView
}()
lazy var lineView: UIView = {
let view = UIView()
view.backgroundColor = UIColor(hexString: AppConst.Color.main)
return view
}()
var sortType = AppConst.SortType.down
var menuView:YD_VMenuView?
var subViewCollectionView:UICollectionView?
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
}
func setupUI() {
// setMenuCollectionView()
setupInfoView()
setSubCollectionView()
}
func setMenuCollectionView() {
menuView = YD_VMenuView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 40),layout:nil)
menuView?.delegate = self
addSubview(menuView!)
}
func setSubCollectionView() {
let subViewLayout = UICollectionViewFlowLayout()
subViewLayout.itemSize = CGSize(width: kScreenWidth, height: kScreenHeight - 90 - 64)
subViewLayout.scrollDirection = .horizontal
subViewLayout.minimumInteritemSpacing = 0
subViewLayout.minimumLineSpacing = 0
// subViewCollectionView = UICollectionView(frame: CGRect(x: 0, y: menuView!.sd_height + infoView.sd_height, width: kScreenWidth, height: kScreenHeight - 90 - 64), collectionViewLayout: subViewLayout)
subViewCollectionView = UICollectionView(frame: CGRect(x: 0, y: infoView.sd_height, width: kScreenWidth, height: kScreenHeight - 90 - 64), collectionViewLayout: subViewLayout)
subViewCollectionView = UICollectionView(frame: CGRect(x: 0, y: infoView.sd_height, width: kScreenWidth, height: kScreenHeight - 90 - 64), collectionViewLayout: subViewLayout)
subViewCollectionView?.delegate = self
subViewCollectionView?.isPagingEnabled = true
subViewCollectionView?.dataSource = self
subViewCollectionView?.bounces = false
subViewCollectionView?.showsVerticalScrollIndicator = false
subViewCollectionView?.showsHorizontalScrollIndicator = false
subViewCollectionView?.backgroundColor = UIColor.white
subViewCollectionView?.register(MenuSubViewCell.self, forCellWithReuseIdentifier: "MenuSubViewCell")
addSubview(subViewCollectionView!)
}
func setupInfoView() {
addSubview(infoView)
// infoView.frame = CGRect(x: 0, y: menuView!.sd_height, width: kScreenWidth, height: 50)
infoView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: 50)
infoView.addSubview(allLabel)
infoView.addSubview(priceTypeButton)
infoView.addSubview(priceChangeButton)
infoView.addSubview(priceImageView)
infoView.addSubview(changeImageView)
changeImageView.snp.makeConstraints { (make) in
make.right.equalTo(-18)
make.height.equalTo(12)
make.width.equalTo(9)
make.centerY.equalTo(infoView)
}
priceChangeButton.snp.makeConstraints { (make) in
make.right.equalTo(changeImageView.snp.left)
make.centerY.equalTo(changeImageView)
make.width.equalTo(100)
make.height.equalTo(20)
}
priceImageView.snp.makeConstraints { (make) in
make.right.equalTo(priceChangeButton.snp.left)
make.width.equalTo(9)
make.height.equalTo(12)
make.centerY.equalTo(infoView)
}
priceTypeButton.snp.makeConstraints { (make) in
make.right.equalTo(priceImageView.snp.left).offset(-20)
make.centerY.equalTo(priceImageView)
}
allLabel.snp.makeConstraints { (make) in
make.left.equalTo(18)
make.width.equalTo(30)
make.height.equalTo(14)
make.centerY.equalTo(infoView)
}
priceChangeButton.addTarget(self, action: #selector(modfySortType), for: .touchUpInside)
let tapGes = UITapGestureRecognizer(target: self, action: #selector(modfySortType))
changeImageView.addGestureRecognizer(tapGes)
}
func modfySortType() {
if sortType.rawValue == 0 {
sortType = AppConst.SortType.up
changeImageView.image = UIImage(named: "marketlist_up")
} else {
sortType = AppConst.SortType.down
changeImageView.image = UIImage(named: "marketlist_down")
}
requestDataWithIndexPath()
}
func requestDataWithIndexPath() {
let cell = subViewCollectionView?.cellForItem(at: selectIndexPath) as? MenuSubViewCell
// cell?.requestStarList(type: selectIndexPath.row, sortType:sortType)
cell?.requestStarList(type: 1, sortType:sortType)
}
func menuViewDidSelect(indexPath: IndexPath) {
subViewCollectionView?.scrollToItem(at: indexPath, at: .left, animated: true)
selectIndexPath = indexPath
perform(#selector(requestDataWithIndexPath), with: nil, afterDelay: 0.5)
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return items == nil ? 0 : items!.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MenuSubViewCell", for: indexPath) as! MenuSubViewCell
cell.delegate = self
return cell
}
func selectItem(starModel:MarketListModel) {
delegate?.selectItem(starModel: starModel)
}
func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
if scrollView == subViewCollectionView {
let index = Int(scrollView.contentOffset.x / kScreenWidth)
let indexPath = IndexPath(item: index, section: 0)
menuView?.selected(index: index)
selectIndexPath = indexPath
requestDataWithIndexPath()
}
}
}
| gpl-3.0 | 385fb31e995b2899572b743b1f568c6f | 37.29108 | 207 | 0.653261 | 4.755685 | false | false | false | false |
eduresende/ios-nd-swift-syntax-swift-3 | Lesson2/L2_Exercises_withSolutions.playground/Contents.swift | 1 | 4355 | import UIKit
//: # Lesson 2 Exercises
//: ## Optionals
//: ### Exercise 1
//: When retrieving a value from a dictionary, Swift returns an optional.
//:
//: 1a) The variable, director, is an optional type. Its value cannot be used until it is unwrapped. Use `if let` to carefully unwrap the value returned by `moviesDict[movie]`
var moviesDict:Dictionary = [ "Star Wars":"George Lucas", "Point Break":"Kathryn Bigelow"]
var movie = "Point Break"
var director = moviesDict[movie]
//: 1b) Test your code by inserting different values for the variable `movie`.
// Solution
//if let director = moviesDict[movie] {
// print ("\(director) directed \(movie)")
//}
//else {
// print("No director found")
//}
//: ### Exercise 2
//: The LoginViewController class below needs a UITextField to hold a user's name. Declare a variable for this text field as a property of the class LoginViewController. Keep in mind that the textfield property will not be initialized until after the view controller is constructed.
class LoginViewController: UIViewController {
}
// Solution
//class LoginViewController: UIViewController {
// var nameTextfield:UITextField!
//}
//: ### Exercise 3
//: The Swift Int type has an initializer that takes a string as a parameter and returns an optional of type Int?.
//:
//: 3a) Finish the code below by safely unwrapping the constant, `number`.
var numericalString = "3"
var number = Int(numericalString)
//TODO: Unwrap number to make the following print statement more readable.
print("\(number) is the magic number.")
// Solution
if let number = number {
print("\(number) is the magic number.")
} else {
print("No magic numbers here.")
}
//: 3b) Change the value of numericalString to "three" and execute the playground again.
// Solution
numericalString = "three"
number = Int(numericalString)
if let number = number {
print("\(number) is the magic number.")
} else {
print("No magic numbers here.")
}
//: ### Exercise 4
//: The class UIViewController has a property called tabBarController. The tabBarController property is an optional of type UITabBarController?. The tabBarController itself holds a tabBar as a property. Complete the code below by filling in the appropriate use of optional chaining to access the tab bar property.
var viewController = UIViewController()
//if let tabBar = //TODO: Optional chaining here {
// print("Here's the tab bar.")
//} else {
// print("No tab bar controller found.")
//}
// Solution
if let tabBar = viewController.tabBarController?.tabBar {
print("Here's the tab bar.")
} else {
print("No tab bar controller found.")
}
//: ### Exercise 5
//: Below is a dictionary of paintings and artists.
//:
//: 5a) The variable, artist, is an optional type. Its value cannot be used until it is unwrapped. Use `if let` to carefully unwrap the value returned by `paintingDict[painting]`.
var paintingDict:Dictionary = [ "Guernica":"Picasso", "Mona Lisa": "da Vinci", "No. 5": "Pollock"]
var painting = "Mona Lisa"
var artist = paintingDict[painting]
//: 5b) Test your code by inserting different values for the variable `painting`.
// Solution
//if let artist = paintingDict[painting] {
// print ("\(artist) painted \(painting)")
//}
//else {
// print("No artist found")
//}
//: ### Exercise 6
//: Set the width of the cancel button below. Notice that the cancelButton variable is declared as an implicitly unwrapped optional.
var anotherViewController = UIViewController()
var cancelButton: UIBarButtonItem!
cancelButton = UIBarButtonItem()
// TODO: Set the width of the cancel button.
// Solution
cancelButton.width = 50
// Properties of implicitly unwrapped optionals are set like any old property, because implicitly unwrapped optionals unwrap automatically.
//: ### Exercise 7
//: The class UIViewController has a property called parentViewController. The parentViewController property is an optional of type UIViewController?. We can't always be sure that a given view controller has a parentViewController. Safely unwrap the parentViewController property below using if let.
var childViewController = UIViewController()
// TODO: Safely unwrap childViewController.parentViewController
// Solution
if let parentVC = childViewController.parent {
print("Here's the parentViewController")
} else {
print("No parents, let's party!")
}
| mit | 68480e18bc0d8213b0a323cad34119ce | 39.700935 | 314 | 0.732262 | 4.350649 | false | false | false | false |
oskarpearson/rileylink_ios | MinimedKitTests/NSDateComponentsTests.swift | 2 | 1389 | //
// NSDateComponentsTests.swift
// RileyLink
//
// Created by Nate Racklyeft on 6/13/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import XCTest
@testable import MinimedKit
class NSDateComponentsTests: XCTestCase {
func testInitWith5BytePumpEventData() {
let input = Data(hexadecimalString: "010018001800440001b8571510")!
let comps = DateComponents(pumpEventData: input, offset: 8)
XCTAssertEqual(2016, comps.year)
XCTAssertEqual(21, comps.day)
XCTAssertEqual(2, comps.month)
XCTAssertEqual(23, comps.hour)
XCTAssertEqual(56, comps.minute)
XCTAssertEqual(1, comps.second)
}
func testInitWith2BytePumpEventData() {
let input = Data(hexadecimalString: "6e351005112ce9b00a000004f001401903b04b00dd01a4013c")!
let comps = DateComponents(pumpEventData: input, offset: 1, length: 2)
XCTAssertEqual(2016, comps.year)
XCTAssertEqual(21, comps.day)
XCTAssertEqual(2, comps.month)
}
func testInitWithGlucoseData() {
let input = Data(hexadecimalString: "0bae0a0e")!
let comps = DateComponents(glucoseEventBytes: input)
XCTAssertEqual(2014, comps.year)
XCTAssertEqual(2, comps.month)
XCTAssertEqual(10, comps.day)
XCTAssertEqual(11, comps.hour)
XCTAssertEqual(46, comps.minute)
}
}
| mit | fb791103cc10107a36934ae6021049bc | 32.047619 | 98 | 0.681556 | 4.106509 | false | true | false | false |
andykog/RAC-MutableCollectionProperty | MutableCollectionProperty/WeakSet.swift | 1 | 2672 |
/// Weak, unordered collection of objects by Adam Preble.
internal struct WeakSet {
/// Maps Element hashValues to arrays of Entry objects.
/// Invalid Entry instances are culled as a side effect of add() and remove()
/// when they touch an object with the same hashValue.
private var contents: [Int: [Entry]] = [:]
init(_ objects: WithID...) {
self.init(objects)
}
init(_ objects: [WithID]) {
for object in objects {
self.insert(object)
}
}
/// Add an element to the set.
mutating func insert(newElement: WithID) {
var entriesAtHash = validEntriesAtHash(newElement.id)
for entry in entriesAtHash {
if let existingElement = entry.element {
if existingElement.id == newElement.id {
return
}
}
}
let entry = Entry(element: newElement)
entriesAtHash.append(entry)
self.contents[newElement.id] = entriesAtHash
}
/// Remove an element from the set.
mutating func remove(removeElement: WithID) {
let entriesAtHash = validEntriesAtHash(removeElement.id)
let entriesMinusElement = entriesAtHash.filter { $0.element?.id != removeElement.id }
if entriesMinusElement.isEmpty {
self.contents[removeElement.id] = nil
} else {
self.contents[removeElement.id] = entriesMinusElement
}
}
// Does the set contain this element?
func contains(element: WithID) -> Bool {
let entriesAtHash = validEntriesAtHash(element.id)
for entry in entriesAtHash {
if entry.element?.id == element.id {
return true
}
}
return false
}
private func validEntriesAtHash(hashValue: Int) -> [Entry] {
if let entries = self.contents[hashValue] {
return entries.filter { $0.element != nil }
} else {
return []
}
}
}
private struct Entry {
weak var element: WithID?
}
// MARK: SequenceType
extension WeakSet : SequenceType {
typealias Generator = AnyGenerator<WithID>
func generate() -> Generator {
var contentsGenerator = self.contents.values.generate()
var entryGenerator = contentsGenerator.next()?.generate()
return AnyGenerator {
if let element = entryGenerator?.next()?.element {
return element
} else {
entryGenerator = contentsGenerator.next()?.generate()
return entryGenerator?.next()?.element
}
}
}
}
| mit | fb7ec5e46a3e4efc84f1448a48573dc2 | 29.022472 | 93 | 0.579341 | 4.712522 | false | false | false | false |
hachinobu/SwiftQiitaClient | SwiftQiitaClient/MyPlayground.playground/Contents.swift | 1 | 4784 | //: Playground - noun: a place where people can play
import UIKit
import Timepiece
import SwiftTask
var str = "Hello, playground"
let dateStr = "2015-12-13T21:33:45+09:00"
let format = dateStr.dateFromFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ")!
let today = NSDate()
func fetchTimeDifference(ISO8601String: String) -> String {
guard let date = ISO8601String.dateFromFormat("yyyy-MM-dd'T'HH:mm:ssZZZZZ") else {
return ""
}
let diff = NSCalendar.currentCalendar().components([.Year, .Month, .Weekday, .Day, .Hour, .Minute, .Second], fromDate: date, toDate: NSDate(), options: [])
if diff.year > 0 {
return "\(diff.year)年"
}
if diff.month > 0 {
return "\(diff.month)ヶ月"
}
if diff.day > 0 {
return "\(diff.day)日"
}
if diff.hour > 0 {
return "\(diff.hour)時間"
}
if diff.minute > 0 {
return "\(diff.minute)分"
}
if diff.second > 0 {
return "\(diff.second)秒"
}
return ""
}
print(fetchTimeDifference(dateStr))
if today.year - format.year > 0 {
print(today.year - format.year)
}
if today.month - format.month > 0 {
print(today.month - format.month)
}
if today.day - format.day > 0 {
print(today.day - format.day)
}
today.day - format.day
if today.hour - format.hour > 0 {
print(today.hour - format.hour)
}
let diff = format.timeIntervalSinceNow
let p = NSCalendar.currentCalendar().components([.Year, .Month, .Weekday, .Day, .Hour, .Minute, .Second], fromDate: format, toDate: NSDate(), options: [])
p.year
p.month
p.day
p.hour
p.minute
let x = NSCalendar.currentCalendar().components([.Year, .Month, .Weekday, .Day, .Hour, .Minute, .Second], fromDate: NSDate())
// components([.Year, .Month, .Weekday, .Day, .Hour, .Minute, .Second], fromDate: NSDate()).
typealias TaskType = Task<Float, Int, NSError>
let task1 = TaskType { (progress, fulfill, reject, configure) -> Void in
return fulfill(1)
}
let task2 = TaskType { (progress, fulfill, reject, configure) -> Void in
return fulfill(2)
}
let task3 = TaskType { (progress, fulfill, reject, configure) -> Void in
return reject(NSError(domain: "domain", code: 10000, userInfo: nil))
return fulfill(3)
}
task1.then { (value, errorInfo: (error: NSError?, isCancelled: Bool)?) -> Int in
return value ?? 0
}.success { (value: Int) -> Void in
print(value)
}
task1.then { (value, errorInfo: (error: NSError?, isCancelled: Bool)?) -> TaskType in
return task2
}.success { (value) -> Void in
print(value)
}
//Task.all([task1, task2, task3]).then { (values, erorrInfo: (error: NSError?, isCancelled: Bool)?) -> TaskType? in
// print("then")
// guard let values = values else {
// return nil
// }
// let total = values.reduce(0, combine: { (var total: Int, value: Int) -> Int in
// return total + value
// })
//
// return TaskType { (progress, fulfill, reject, configure) -> Void in
// return reject(NSError(domain: "domain", code: 10000, userInfo: nil))
// }
//
//}.success { (task: TaskType?) -> Void in
// print("succ")
// task!.success { (value: Int) -> Void in
// print(value)
// }.failure({ (error, isCancelled) -> Void in
// print("failure")
// })
//}.failure { (error, isCancelled) -> Void in
// print("fail")
//}
Task.all([task1, task2, task3]).success { (values) -> TaskType in
print("success")
let total = values.reduce(0, combine: { (var total: Int, value: Int) -> Int in
return total + value
})
return TaskType { (progress, fulfill, reject, configure) -> Void in
return fulfill(total)
}
}.success { (value: Int) -> Void in
print(value)
}.failure { (error, isCancelled) -> Void in
print("fail")
}
Task.all([task1, task2, task3]).success { (values) -> Void in
print("success")
TaskType { (progress, fulfill, reject, configure) -> Void in
return fulfill(10)
}.success { value -> Void in
print(value)
}
}.failure { (error, isCancelled) -> Void in
print("fail")
}
Task.all([task1, task2]).success { values -> Void in
task3.success { (value) -> Void in
print(value)
}.failure { (error, isCancelled) -> Void in
print("task3 failure")
}
}.failure { (error, isCancelled) -> Void in
print("all failure")
}
Task.any([task3, task2, task1]).success { (value: Int) -> Void in
print("success \(value)")
}.failure { (error, isCancelled) -> Void in
print("failure")
}
Task.some([task1, task2, task3]).success { (values) -> Void in
print("value \(values)")
}.failure { (error, isCancelled) -> Void in
print("fail")
}
| mit | 28285653fb75b4bfb77d2ebb825883bd | 24.094737 | 159 | 0.597945 | 3.437635 | false | false | false | false |
tokenlab/TKCurrencyTextField | Example/TKCurrencyTextField.swift | 1 | 4208 | //
// TKCurrencyTextField.swift
// Tokenlab
//
// Created by Daniele Boscolo on 10/05/17.
// Copyright © 2017 Tokenlab. All rights reserved.
//
import UIKit
@IBDesignable open class TKCurrencyTextField: UITextField {
@IBInspectable var maxDigits: Int = 15
@IBInspectable var defaultValue: Double = 0.00
fileprivate var _maskHandler: ((_ textField: UITextField, _ range: NSRange, _ replacementString: String) -> ())? = nil
var maskHandler: ((_ textField: UITextField, _ range: NSRange, _ replacementString: String) -> ())? {
get {
return _maskHandler
}
}
// MARK: - init functions
override init(frame: CGRect) {
super.init(frame: frame)
initTextField()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initTextField()
}
func initTextField(){
keyboardType = UIKeyboardType.decimalPad
setAmount(defaultValue)
let currencyHandler: ((_ textField: UITextField, _ range: NSRange, _ replacementString: String) -> ()) = {
(textField, range, replacementString) in
let nsString: NSString = textField.text as NSString? ?? ""
let text = nsString.replacingCharacters(in: range, with: replacementString)
let cleanNumericString: String = text.onlyNumberString
var textFieldNumber: Double = 0.0
if cleanNumericString.characters.count > self.maxDigits {
let limitString = cleanNumericString.substring(to: cleanNumericString.characters.index(cleanNumericString.startIndex, offsetBy: self.maxDigits))
textFieldNumber = (limitString as NSString).doubleValue
} else {
textFieldNumber = (cleanNumericString as NSString).doubleValue
}
let textFieldNewValue = textFieldNumber/100
let textFieldStringValue = textFieldNewValue.currencyStringValue
textField.text = textFieldStringValue
}
setMaskHandler(currencyHandler)
}
func setMaskHandler(_ handler: ((_ textField: UITextField, _ range: NSRange, _ replacementString: String)->())?) {
_maskHandler = handler
addTarget(self, action: #selector(textDidChange), for: .editingChanged)
}
func textDidChange() {
// get the original position of the cursor
let cursorOffset = getOriginalCursorPosition();
let textFieldLength = text?.characters.count
maskHandler?(self, NSRange(), "")
// set the cursor back to its original poistion
setCursorOriginalPosition(cursorOffset, oldTextFieldLength: textFieldLength)
}
fileprivate func getOriginalCursorPosition() -> Int {
var cursorOffset: Int = 0
let startPosition: UITextPosition = self.beginningOfDocument
if let selectedTextRange = self.selectedTextRange{
cursorOffset = self.offset(from: startPosition, to: selectedTextRange.start)
}
return cursorOffset
}
fileprivate func setCursorOriginalPosition(_ cursorOffset: Int, oldTextFieldLength : Int?){
let newLength = self.text?.characters.count
let startPosition : UITextPosition = self.beginningOfDocument
if let oldTextFieldLength = oldTextFieldLength, let newLength = newLength, oldTextFieldLength > cursorOffset {
let newOffset = newLength - oldTextFieldLength + cursorOffset
let newCursorPosition = self.position(from: startPosition, offset: newOffset)
if let newCursorPosition = newCursorPosition{
let newSelectedRange = self.textRange(from: newCursorPosition, to: newCursorPosition)
self.selectedTextRange = newSelectedRange
}
}
}
// MARK: - Custom functions
func setAmount (_ amount: Double) {
let textFieldStringValue = amount.currencyStringValue
text = textFieldStringValue
}
var getAmount: Double {
if let text = text {
return text.currencyStringToDouble
}
return defaultValue
}
}
| mit | 60c13cddaac8f54d1dea43ba3ddd4902 | 37.245455 | 160 | 0.643451 | 5.39359 | false | false | false | false |
czechboy0/Buildasaur | BuildaKit/NetworkUtils.swift | 2 | 4589 | //
// NetworkUtils.swift
// Buildasaur
//
// Created by Honza Dvorsky on 07/03/2015.
// Copyright (c) 2015 Honza Dvorsky. All rights reserved.
//
import Foundation
import BuildaGitServer
import BuildaUtils
import XcodeServerSDK
public class NetworkUtils {
public typealias VerificationCompletion = (success: Bool, error: ErrorType?) -> ()
public class func checkAvailabilityOfServiceWithProject(project: Project, completion: VerificationCompletion) {
self.checkService(project, completion: { success, error in
if !success {
completion(success: false, error: error)
return
}
//now test ssh keys
let credentialValidationBlueprint = project.createSourceControlBlueprintForCredentialVerification()
self.checkValidityOfSSHKeys(credentialValidationBlueprint, completion: { (success, error) -> () in
if success {
Log.verbose("Finished blueprint validation with success!")
} else {
Log.verbose("Finished blueprint validation with error: \(error)")
}
//now complete
completion(success: success, error: error)
})
})
}
private class func checkService(project: Project, completion: VerificationCompletion) {
let auth = project.config.value.serverAuthentication
let service = auth!.service
let server = SourceServerFactory().createServer(service, auth: auth)
//check if we can get the repo and verify permissions
guard let repoName = project.serviceRepoName() else {
completion(success: false, error: Error.withInfo("Invalid repo name"))
return
}
//we have a repo name
server.getRepo(repoName, completion: { (repo, error) -> () in
if error != nil {
completion(success: false, error: error)
return
}
if let repo = repo {
let permissions = repo.permissions
let readPermission = permissions.read
let writePermission = permissions.write
//look at the permissions in the PR metadata
if !readPermission {
completion(success: false, error: Error.withInfo("Missing read permission for repo"))
} else if !writePermission {
completion(success: false, error: Error.withInfo("Missing write permission for repo"))
} else {
//now complete
completion(success: true, error: nil)
}
} else {
completion(success: false, error: Error.withInfo("Couldn't find repo permissions in \(service.prettyName()) response"))
}
})
}
public class func checkAvailabilityOfXcodeServerWithCurrentSettings(config: XcodeServerConfig, completion: (success: Bool, error: NSError?) -> ()) {
let xcodeServer = XcodeServerFactory.server(config)
//the way we check availability is first by logging out (does nothing if not logged in) and then
//calling getUserCanCreateBots, which, if necessary, authenticates before resolving to true or false in JSON.
xcodeServer.logout { (success, error) -> () in
if let error = error {
completion(success: false, error: error)
return
}
xcodeServer.getUserCanCreateBots({ (canCreateBots, error) -> () in
if let error = error {
completion(success: false, error: error)
return
}
completion(success: canCreateBots, error: nil)
})
}
}
class func checkValidityOfSSHKeys(blueprint: SourceControlBlueprint, completion: (success: Bool, error: NSError?) -> ()) {
let blueprintDict = blueprint.dictionarify()
let r = SSHKeyVerification.verifyBlueprint(blueprintDict)
//based on the return value, either succeed or fail
if r.terminationStatus == 0 {
completion(success: true, error: nil)
} else {
completion(success: false, error: Error.withInfo(r.standardError))
}
}
}
| mit | 2b140f74012e0d288edb395f2b34efb2 | 36.92562 | 152 | 0.56265 | 5.589525 | false | false | false | false |
shuoli84/RxSwift | RxDataSourceStarterKit/DataSources/RxTableViewSectionedDataSource.swift | 3 | 5323 | //
// RxTableViewDataSource.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 6/15/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxSwift
import RxCocoa
import UIKit
// objc monkey business
public class _RxTableViewSectionedDataSource : NSObject
, UITableViewDataSource {
func _numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return _numberOfSectionsInTableView(tableView)
}
func _tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return _tableView(tableView, numberOfRowsInSection: section)
}
func _tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return (nil as UITableViewCell?)!
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return _tableView(tableView, cellForRowAtIndexPath: indexPath)
}
func _tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return nil
}
public func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return _tableView(tableView, titleForHeaderInSection: section)
}
func _tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return nil
}
public func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return _tableView(tableView, titleForFooterInSection: section)
}
}
public class RxTableViewSectionedDataSource<S: SectionModelType> : _RxTableViewSectionedDataSource {
public typealias I = S.Item
public typealias Section = S
public typealias CellFactory = (UITableView, NSIndexPath, I) -> UITableViewCell
public typealias IncrementalUpdateObserver = ObserverOf<Changeset<S>>
public typealias IncrementalUpdateDisposeKey = Bag<IncrementalUpdateObserver>.KeyType
// This structure exists because model can be mutable
// In that case current state value should be preserved.
// The state that needs to be preserved is ordering of items in section
// and their relationship with section.
// If particular item is mutable, that is irrelevant for this logic to function
// properly.
public typealias SectionModelSnapshot = SectionModel<S, I>
var sectionModels: [SectionModelSnapshot] = []
public func sectionAtIndex(section: Int) -> S {
return self.sectionModels[section].model
}
public func itemAtIndexPath(indexPath: NSIndexPath) -> I {
return self.sectionModels[indexPath.section].items[indexPath.item]
}
var incrementalUpdateObservers: Bag<IncrementalUpdateObserver> = Bag()
public func setSections(sections: [S]) {
self.sectionModels = sections.map { SectionModelSnapshot(model: $0, items: $0.items) }
}
public var cellFactory: CellFactory! = nil
public var titleForHeaderInSection: ((section: Int) -> String)?
public var titleForFooterInSection: ((section: Int) -> String)?
public var rowAnimation: UITableViewRowAnimation = .Automatic
public override init() {
super.init()
self.cellFactory = { [weak self] _ in
if let strongSelf = self {
precondition(false, "There is a minor problem. `cellFactory` property on \(strongSelf) was not set. Please set it manually, or use one of the `rx_subscribeTo` methods.")
}
return (nil as UITableViewCell!)!
}
}
// observers
public func addIncrementalUpdatesObserver(observer: IncrementalUpdateObserver) -> IncrementalUpdateDisposeKey {
return incrementalUpdateObservers.put(observer)
}
public func removeIncrementalUpdatesObserver(key: IncrementalUpdateDisposeKey) {
let element = incrementalUpdateObservers.removeKey(key)
precondition(element != nil, "Element removal failed")
}
// UITableViewDataSource
override func _numberOfSectionsInTableView(tableView: UITableView) -> Int {
return sectionModels.count
}
override func _tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return sectionModels[section].items.count
}
override func _tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
precondition(indexPath.item < sectionModels[indexPath.section].items.count)
return cellFactory(tableView, indexPath, itemAtIndexPath(indexPath))
}
override func _tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return titleForHeaderInSection?(section: section)
}
override func _tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return titleForFooterInSection?(section: section)
}
} | mit | cbb66f7b9814ab044e619996f686c4c7 | 35.465753 | 185 | 0.694721 | 5.539022 | false | false | false | false |
tjw/swift | test/attr/attr_availability.swift | 1 | 67038 | // RUN: %target-typecheck-verify-swift
@available(*, unavailable)
func unavailable_func() {}
@available(*, unavailable, message: "message")
func unavailable_func_with_message() {}
@available(tvOS, unavailable)
@available(watchOS, unavailable)
@available(iOS, unavailable)
@available(OSX, unavailable)
func unavailable_multiple_platforms() {}
@available // expected-error {{expected '(' in 'available' attribute}}
func noArgs() {}
@available(*) // expected-error {{expected ',' in 'available' attribute}}
func noKind() {}
@available(badPlatform, unavailable) // expected-warning {{unknown platform 'badPlatform' for attribute 'available'}}
func unavailable_bad_platform() {}
// Handle unknown platform.
@available(HAL9000, unavailable) // expected-warning {{unknown platform 'HAL9000'}}
func availabilityUnknownPlatform() {}
// <rdar://problem/17669805> Availability can't appear on a typealias
@available(*, unavailable, message: "oh no you don't")
typealias int = Int // expected-note {{'int' has been explicitly marked unavailable here}}
@available(*, unavailable, renamed: "Float")
typealias float = Float // expected-note {{'float' has been explicitly marked unavailable here}}
protocol MyNewerProtocol {}
@available(*, unavailable, renamed: "MyNewerProtocol")
protocol MyOlderProtocol {} // expected-note {{'MyOlderProtocol' has been explicitly marked unavailable here}}
extension Int: MyOlderProtocol {} // expected-error {{'MyOlderProtocol' has been renamed to 'MyNewerProtocol'}}
struct MyCollection<Element> {
@available(*, unavailable, renamed: "Element")
typealias T = Element // expected-note 2{{'T' has been explicitly marked unavailable here}}
func foo(x: T) { } // expected-error {{'T' has been renamed to 'Element'}} {{15-16=Element}}
}
extension MyCollection {
func append(element: T) { } // expected-error {{'T' has been renamed to 'Element'}} {{24-25=Element}}
}
@available(*, unavailable, renamed: "MyCollection")
typealias YourCollection<Element> = MyCollection<Element> // expected-note {{'YourCollection' has been explicitly marked unavailable here}}
var x : YourCollection<Int> // expected-error {{'YourCollection' has been renamed to 'MyCollection'}}{{9-23=MyCollection}}
var x : int // expected-error {{'int' is unavailable: oh no you don't}}
var y : float // expected-error {{'float' has been renamed to 'Float'}}{{9-14=Float}}
// Encoded message
@available(*, unavailable, message: "This message has a double quote \"")
func unavailableWithDoubleQuoteInMessage() {} // expected-note {{'unavailableWithDoubleQuoteInMessage()' has been explicitly marked unavailable here}}
func useWithEscapedMessage() {
unavailableWithDoubleQuoteInMessage() // expected-error {{'unavailableWithDoubleQuoteInMessage()' is unavailable: This message has a double quote \"}}
}
// More complicated parsing.
@available(OSX, message: "x", unavailable)
let _: Int
@available(OSX, introduced: 1, deprecated: 2.0, obsoleted: 3.0.0)
let _: Int
@available(OSX, introduced: 1.0.0, deprecated: 2.0, obsoleted: 3, unavailable, renamed: "x")
let _: Int
// Meaningless but accepted.
@available(OSX, message: "x")
let _: Int
// Parse errors.
@available() // expected-error{{expected platform name or '*' for 'available' attribute}}
let _: Int
@available(OSX,) // expected-error{{expected 'available' option such as 'unavailable', 'introduced', 'deprecated', 'obsoleted', 'message', or 'renamed'}}
let _: Int
@available(OSX, message) // expected-error{{expected ':' after 'message' in 'available' attribute}}
let _: Int
@available(OSX, message: ) // expected-error{{expected string literal in 'available' attribute}}
let _: Int
@available(OSX, message: x) // expected-error{{expected string literal in 'available' attribute}}
let _: Int
@available(OSX, unavailable:) // expected-error{{expected ')' in 'available' attribute}} expected-error{{expected declaration}}
let _: Int
@available(OSX, introduced) // expected-error{{expected ':' after 'introduced' in 'available' attribute}}
let _: Int
@available(OSX, introduced: ) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: x) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: 1.x) // expected-error{{expected ')' in 'available' attribute}} expected-error {{expected declaration}}
let _: Int
@available(OSX, introduced: 1.0.x) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: 0x1) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: 1.0e4) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: -1) // expected-error{{expected version number in 'available' attribute}} expected-error{{expected declaration}}
let _: Int
@available(OSX, introduced: 1.0.1e4) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(OSX, introduced: 1.0.0x4) // expected-error{{expected version number in 'available' attribute}}
let _: Int
@available(*, renamed: "bad name") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "_") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "a+b") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "a(") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "a(:)") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, renamed: "a(:b:)") // expected-error{{'renamed' argument of 'available' attribute must be an operator, identifier, or full function name, optionally prefixed by a type name}}
let _: Int
@available(*, deprecated, unavailable, message: "message") // expected-error{{'available' attribute cannot be both unconditionally 'unavailable' and 'deprecated'}}
struct BadUnconditionalAvailability { };
@available(*, unavailable, message="oh no you don't") // expected-error {{'=' has been replaced with ':' in attribute arguments}} {{35-36=: }}
typealias EqualFixIt1 = Int
@available(*, unavailable, message = "oh no you don't") // expected-error {{'=' has been replaced with ':' in attribute arguments}} {{36-37=:}}
typealias EqualFixIt2 = Int
// Encoding in messages
@available(*, deprecated, message: "Say \"Hi\"")
func deprecated_func_with_message() {}
// 'PANDA FACE' (U+1F43C)
@available(*, deprecated, message: "Pandas \u{1F43C} are cute")
struct DeprecatedTypeWithMessage { }
func use_deprecated_with_message() {
deprecated_func_with_message() // expected-warning{{'deprecated_func_with_message()' is deprecated: Say \"Hi\"}}
var _: DeprecatedTypeWithMessage // expected-warning{{'DeprecatedTypeWithMessage' is deprecated: Pandas \u{1F43C} are cute}}
}
@available(*, deprecated, message: "message")
func use_deprecated_func_with_message2() {
deprecated_func_with_message() // no diagnostic
}
@available(*, deprecated, renamed: "blarg")
func deprecated_func_with_renamed() {}
@available(*, deprecated, message: "blarg is your friend", renamed: "blarg")
func deprecated_func_with_message_renamed() {}
@available(*, deprecated, renamed: "wobble")
struct DeprecatedTypeWithRename { }
func use_deprecated_with_renamed() {
deprecated_func_with_renamed() // expected-warning{{'deprecated_func_with_renamed()' is deprecated: renamed to 'blarg'}}
// expected-note@-1{{use 'blarg'}}{{3-31=blarg}}
deprecated_func_with_message_renamed() //expected-warning{{'deprecated_func_with_message_renamed()' is deprecated: blarg is your friend}}
// expected-note@-1{{use 'blarg'}}{{3-39=blarg}}
var _: DeprecatedTypeWithRename // expected-warning{{'DeprecatedTypeWithRename' is deprecated: renamed to 'wobble'}}
// expected-note@-1{{use 'wobble'}}{{10-34=wobble}}
}
// Short form of @available()
@available(iOS 8.0, *)
func functionWithShortFormIOSAvailable() {}
@available(iOS 8, *)
func functionWithShortFormIOSVersionNoPointAvailable() {}
@available(iOS 8.0, OSX 10.10.3, *)
func functionWithShortFormIOSOSXAvailable() {}
@available(iOS 8.0 // expected-error {{must handle potential future platforms with '*'}} {{19-19=, *}}
func shortFormMissingParen() { // expected-error {{expected ')' in 'available' attribute}}
}
@available(iOS 8.0, // expected-error {{expected platform name}}
func shortFormMissingPlatform() {
}
@available(iOS 8.0, *
func shortFormMissingParenAfterWildcard() { // expected-error {{expected ')' in 'available' attribute}}
}
@available(*) // expected-error {{expected ',' in 'available' attribute}}
func onlyWildcardInAvailable() {}
@available(iOS 8.0, *, OSX 10.10.3)
func shortFormWithWildcardInMiddle() {}
@available(iOS 8.0, OSX 10.10.3) // expected-error {{must handle potential future platforms with '*'}} {{32-32=, *}}
func shortFormMissingWildcard() {}
@availability(OSX, introduced: 10.10) // expected-error {{'@availability' has been renamed to '@available'}} {{2-14=available}}
func someFuncUsingOldAttribute() { }
// <rdar://problem/23853709> Compiler crash on call to unavailable "print"
@available(*, unavailable, message: "Please use the 'to' label for the target stream: 'print((...), to: &...)'")
func print<T>(_: T, _: inout TextOutputStream) {} // expected-note {{}}
func TextOutputStreamTest(message: String, to: inout TextOutputStream) {
print(message, &to) // expected-error {{'print' is unavailable: Please use the 'to' label for the target stream: 'print((...), to: &...)'}}
}
// expected-note@+1{{'T' has been explicitly marked unavailable here}}
struct UnavailableGenericParam<@available(*, unavailable, message: "nope") T> {
func f(t: T) { } // expected-error{{'T' is unavailable: nope}}
}
struct DummyType {}
@available(*, unavailable, renamed: "&+")
func +(x: DummyType, y: DummyType) {} // expected-note {{here}}
@available(*, deprecated, renamed: "&-")
func -(x: DummyType, y: DummyType) {}
func testOperators(x: DummyType, y: DummyType) {
x + y // expected-error {{'+' has been renamed to '&+'}} {{5-6=&+}}
x - y // expected-warning {{'-' is deprecated: renamed to '&-'}} expected-note {{use '&-' instead}} {{5-6=&-}}
}
@available(*, unavailable, renamed: "DummyType.foo")
func unavailableMember() {} // expected-note {{here}}
@available(*, deprecated, renamed: "DummyType.bar")
func deprecatedMember() {}
@available(*, unavailable, renamed: "DummyType.Inner.foo")
func unavailableNestedMember() {} // expected-note {{here}}
@available(*, unavailable, renamed: "DummyType.Foo")
struct UnavailableType {} // expected-note {{here}}
@available(*, deprecated, renamed: "DummyType.Bar")
typealias DeprecatedType = Int
func testGlobalToMembers() {
unavailableMember() // expected-error {{'unavailableMember()' has been renamed to 'DummyType.foo'}} {{3-20=DummyType.foo}}
deprecatedMember() // expected-warning {{'deprecatedMember()' is deprecated: renamed to 'DummyType.bar'}} expected-note {{use 'DummyType.bar' instead}} {{3-19=DummyType.bar}}
unavailableNestedMember() // expected-error {{'unavailableNestedMember()' has been renamed to 'DummyType.Inner.foo'}} {{3-26=DummyType.Inner.foo}}
let x: UnavailableType? = nil // expected-error {{'UnavailableType' has been renamed to 'DummyType.Foo'}} {{10-25=DummyType.Foo}}
_ = x
let y: DeprecatedType? = nil // expected-warning {{'DeprecatedType' is deprecated: renamed to 'DummyType.Bar'}} expected-note {{use 'DummyType.Bar' instead}} {{10-24=DummyType.Bar}}
_ = y
}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableArgNames(a: Int) {} // expected-note {{here}}
@available(*, deprecated, renamed: "moreShinyLabeledArguments(example:)")
func deprecatedArgNames(b: Int) {}
@available(*, unavailable, renamed: "DummyType.shinyLabeledArguments(example:)")
func unavailableMemberArgNames(a: Int) {} // expected-note {{here}}
@available(*, deprecated, renamed: "DummyType.moreShinyLabeledArguments(example:)")
func deprecatedMemberArgNames(b: Int) {}
@available(*, unavailable, renamed: "DummyType.shinyLabeledArguments(example:)", message: "ha")
func unavailableMemberArgNamesMsg(a: Int) {} // expected-note {{here}}
@available(*, deprecated, renamed: "DummyType.moreShinyLabeledArguments(example:)", message: "ha")
func deprecatedMemberArgNamesMsg(b: Int) {}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableNoArgs() {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:)")
func unavailableSame(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableUnnamedSame(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableNewlyUnnamed(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ:)")
func unavailableVeryLongArgNames(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableMultiSame(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:another:)")
func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.init(other:)")
func unavailableInit(a: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "Foo.Bar.init(other:)")
func unavailableNestedInit(a: Int) {} // expected-note 2 {{here}}
func testArgNames() {
unavailableArgNames(a: 0) // expected-error {{'unavailableArgNames(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{3-22=shinyLabeledArguments}} {{23-24=example}}
deprecatedArgNames(b: 1) // expected-warning {{'deprecatedArgNames(b:)' is deprecated: renamed to 'moreShinyLabeledArguments(example:)'}} expected-note {{use 'moreShinyLabeledArguments(example:)' instead}} {{3-21=moreShinyLabeledArguments}} {{22-23=example}}
unavailableMemberArgNames(a: 0) // expected-error {{'unavailableMemberArgNames(a:)' has been replaced by 'DummyType.shinyLabeledArguments(example:)'}} {{3-28=DummyType.shinyLabeledArguments}} {{29-30=example}}
deprecatedMemberArgNames(b: 1) // expected-warning {{'deprecatedMemberArgNames(b:)' is deprecated: replaced by 'DummyType.moreShinyLabeledArguments(example:)'}} expected-note {{use 'DummyType.moreShinyLabeledArguments(example:)' instead}} {{3-27=DummyType.moreShinyLabeledArguments}} {{28-29=example}}
unavailableMemberArgNamesMsg(a: 0) // expected-error {{'unavailableMemberArgNamesMsg(a:)' has been replaced by 'DummyType.shinyLabeledArguments(example:)': ha}} {{3-31=DummyType.shinyLabeledArguments}} {{32-33=example}}
deprecatedMemberArgNamesMsg(b: 1) // expected-warning {{'deprecatedMemberArgNamesMsg(b:)' is deprecated: ha}} expected-note {{use 'DummyType.moreShinyLabeledArguments(example:)' instead}} {{3-30=DummyType.moreShinyLabeledArguments}} {{31-32=example}}
unavailableNoArgs() // expected-error {{'unavailableNoArgs()' has been renamed to 'shinyLabeledArguments()'}} {{3-20=shinyLabeledArguments}}
unavailableSame(a: 0) // expected-error {{'unavailableSame(a:)' has been renamed to 'shinyLabeledArguments(a:)'}} {{3-18=shinyLabeledArguments}}
unavailableUnnamed(0) // expected-error {{'unavailableUnnamed' has been renamed to 'shinyLabeledArguments(example:)'}} {{3-21=shinyLabeledArguments}} {{22-22=example: }}
unavailableUnnamedSame(0) // expected-error {{'unavailableUnnamedSame' has been renamed to 'shinyLabeledArguments(_:)'}} {{3-25=shinyLabeledArguments}}
unavailableNewlyUnnamed(a: 0) // expected-error {{'unavailableNewlyUnnamed(a:)' has been renamed to 'shinyLabeledArguments(_:)'}} {{3-26=shinyLabeledArguments}} {{27-30=}}
unavailableVeryLongArgNames(a: 0) // expected-error {{'unavailableVeryLongArgNames(a:)' has been renamed to 'shinyLabeledArguments(veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ:)'}} {{3-30=shinyLabeledArguments}} {{31-32=veryLongNameToOverflowASmallStringABCDEFGHIJKLMNOPQRSTUVWXYZ}}
unavailableMultiSame(a: 0, b: 1) // expected-error {{'unavailableMultiSame(a:b:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-23=shinyLabeledArguments}}
unavailableMultiUnnamed(0, 1) // expected-error {{'unavailableMultiUnnamed' has been renamed to 'shinyLabeledArguments(example:another:)'}} {{3-26=shinyLabeledArguments}} {{27-27=example: }} {{30-30=another: }}
unavailableMultiUnnamedSame(0, 1) // expected-error {{'unavailableMultiUnnamedSame' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{3-30=shinyLabeledArguments}}
unavailableMultiNewlyUnnamed(a: 0, b: 1) // expected-error {{'unavailableMultiNewlyUnnamed(a:b:)' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{3-31=shinyLabeledArguments}} {{32-35=}} {{38-41=}}
unavailableInit(a: 0) // expected-error {{'unavailableInit(a:)' has been replaced by 'Int.init(other:)'}} {{3-18=Int}} {{19-20=other}}
let fn = unavailableInit // expected-error {{'unavailableInit(a:)' has been replaced by 'Int.init(other:)'}} {{12-27=Int.init}}
fn(1)
unavailableNestedInit(a: 0) // expected-error {{'unavailableNestedInit(a:)' has been replaced by 'Foo.Bar.init(other:)'}} {{3-24=Foo.Bar}} {{25-26=other}}
let fn2 = unavailableNestedInit // expected-error {{'unavailableNestedInit(a:)' has been replaced by 'Foo.Bar.init(other:)'}} {{13-34=Foo.Bar.init}}
fn2(1)
}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableTooFew(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableTooFewUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableTooMany(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableTooManyUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:)")
func unavailableNoArgsTooMany() {} // expected-note {{here}}
func testRenameArgMismatch() {
unavailableTooFew(a: 0) // expected-error{{'unavailableTooFew(a:)' has been renamed to 'shinyLabeledArguments()'}} {{3-20=shinyLabeledArguments}}
unavailableTooFewUnnamed(0) // expected-error{{'unavailableTooFewUnnamed' has been renamed to 'shinyLabeledArguments()'}} {{3-27=shinyLabeledArguments}}
unavailableTooMany(a: 0) // expected-error{{'unavailableTooMany(a:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-21=shinyLabeledArguments}}
unavailableTooManyUnnamed(0) // expected-error{{'unavailableTooManyUnnamed' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{3-28=shinyLabeledArguments}}
unavailableNoArgsTooMany() // expected-error{{'unavailableNoArgsTooMany()' has been renamed to 'shinyLabeledArguments(a:)'}} {{3-27=shinyLabeledArguments}}
}
@available(*, unavailable, renamed: "Int.foo(self:)")
func unavailableInstance(a: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "Int.foo(self:)")
func unavailableInstanceUnlabeled(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:other:)")
func unavailableInstanceFirst(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(other:self:)")
func unavailableInstanceSecond(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(_:self:c:)")
func unavailableInstanceSecondOfThree(a: Int, b: Int, c: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:)", message: "blah")
func unavailableInstanceMessage(a: Int) {} // expected-note {{here}}
@available(*, deprecated, renamed: "Int.foo(self:)")
func deprecatedInstance(a: Int) {}
@available(*, deprecated, renamed: "Int.foo(self:)", message: "blah")
func deprecatedInstanceMessage(a: Int) {}
@available(*, unavailable, renamed: "Foo.Bar.foo(self:)")
func unavailableNestedInstance(a: Int) {} // expected-note {{here}}
func testRenameInstance() {
unavailableInstance(a: 0) // expected-error{{'unavailableInstance(a:)' has been replaced by instance method 'Int.foo()'}} {{3-22=0.foo}} {{23-27=}}
unavailableInstanceUnlabeled(0) // expected-error{{'unavailableInstanceUnlabeled' has been replaced by instance method 'Int.foo()'}} {{3-31=0.foo}} {{32-33=}}
unavailableInstanceFirst(a: 0, b: 1) // expected-error{{'unavailableInstanceFirst(a:b:)' has been replaced by instance method 'Int.foo(other:)'}} {{3-27=0.foo}} {{28-34=}} {{34-35=other}}
unavailableInstanceSecond(a: 0, b: 1) // expected-error{{'unavailableInstanceSecond(a:b:)' has been replaced by instance method 'Int.foo(other:)'}} {{3-28=1.foo}} {{29-30=other}} {{33-39=}}
unavailableInstanceSecondOfThree(a: 0, b: 1, c: 2) // expected-error{{'unavailableInstanceSecondOfThree(a:b:c:)' has been replaced by instance method 'Int.foo(_:c:)'}} {{3-35=1.foo}} {{36-39=}} {{42-48=}}
unavailableInstance(a: 0 + 0) // expected-error{{'unavailableInstance(a:)' has been replaced by instance method 'Int.foo()'}} {{3-22=(0 + 0).foo}} {{23-31=}}
unavailableInstanceMessage(a: 0) // expected-error{{'unavailableInstanceMessage(a:)' has been replaced by instance method 'Int.foo()': blah}} {{3-29=0.foo}} {{30-34=}}
deprecatedInstance(a: 0) // expected-warning{{'deprecatedInstance(a:)' is deprecated: replaced by instance method 'Int.foo()'}} expected-note{{use 'Int.foo()' instead}} {{3-21=0.foo}} {{22-26=}}
deprecatedInstanceMessage(a: 0) // expected-warning{{'deprecatedInstanceMessage(a:)' is deprecated: blah}} expected-note{{use 'Int.foo()' instead}} {{3-28=0.foo}} {{29-33=}}
unavailableNestedInstance(a: 0) // expected-error{{'unavailableNestedInstance(a:)' has been replaced by instance method 'Foo.Bar.foo()'}} {{3-28=0.foo}} {{29-33=}}
}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)")
func unavailableInstanceTooFew(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)")
func unavailableInstanceTooFewUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:b:)")
func unavailableInstanceTooMany(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:b:)")
func unavailableInstanceTooManyUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.shinyLabeledArguments(self:)")
func unavailableInstanceNoArgsTooMany() {} // expected-note {{here}}
func testRenameInstanceArgMismatch() {
unavailableInstanceTooFew(a: 0, b: 1) // expected-error{{'unavailableInstanceTooFew(a:b:)' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}}
unavailableInstanceTooFewUnnamed(0, 1) // expected-error{{'unavailableInstanceTooFewUnnamed' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}}
unavailableInstanceTooMany(a: 0) // expected-error{{'unavailableInstanceTooMany(a:)' has been replaced by instance method 'Int.shinyLabeledArguments(b:)'}} {{none}}
unavailableInstanceTooManyUnnamed(0) // expected-error{{'unavailableInstanceTooManyUnnamed' has been replaced by instance method 'Int.shinyLabeledArguments(b:)'}} {{none}}
unavailableInstanceNoArgsTooMany() // expected-error{{'unavailableInstanceNoArgsTooMany()' has been replaced by instance method 'Int.shinyLabeledArguments()'}} {{none}}
}
@available(*, unavailable, renamed: "getter:Int.prop(self:)")
func unavailableInstanceProperty(a: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "getter:Int.prop(self:)")
func unavailableInstancePropertyUnlabeled(_ a: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "getter:Int.prop()")
func unavailableClassProperty() {} // expected-note {{here}}
@available(*, unavailable, renamed: "getter:global()")
func unavailableGlobalProperty() {} // expected-note {{here}}
@available(*, unavailable, renamed: "getter:Int.prop(self:)", message: "blah")
func unavailableInstancePropertyMessage(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "getter:Int.prop()", message: "blah")
func unavailableClassPropertyMessage() {} // expected-note {{here}}
@available(*, unavailable, renamed: "getter:global()", message: "blah")
func unavailableGlobalPropertyMessage() {} // expected-note {{here}}
@available(*, deprecated, renamed: "getter:Int.prop(self:)")
func deprecatedInstanceProperty(a: Int) {}
@available(*, deprecated, renamed: "getter:Int.prop()")
func deprecatedClassProperty() {}
@available(*, deprecated, renamed: "getter:global()")
func deprecatedGlobalProperty() {}
@available(*, deprecated, renamed: "getter:Int.prop(self:)", message: "blah")
func deprecatedInstancePropertyMessage(a: Int) {}
@available(*, deprecated, renamed: "getter:Int.prop()", message: "blah")
func deprecatedClassPropertyMessage() {}
@available(*, deprecated, renamed: "getter:global()", message: "blah")
func deprecatedGlobalPropertyMessage() {}
func testRenameGetters() {
unavailableInstanceProperty(a: 1) // expected-error{{'unavailableInstanceProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=1.prop}} {{30-36=}}
unavailableInstancePropertyUnlabeled(1) // expected-error{{'unavailableInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-39=1.prop}} {{39-42=}}
unavailableInstanceProperty(a: 1 + 1) // expected-error{{'unavailableInstanceProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=(1 + 1).prop}} {{30-40=}}
unavailableInstancePropertyUnlabeled(1 + 1) // expected-error{{'unavailableInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-39=(1 + 1).prop}} {{39-46=}}
unavailableClassProperty() // expected-error{{'unavailableClassProperty()' has been replaced by property 'Int.prop'}} {{3-27=Int.prop}} {{27-29=}}
unavailableGlobalProperty() // expected-error{{'unavailableGlobalProperty()' has been replaced by 'global'}} {{3-28=global}} {{28-30=}}
unavailableInstancePropertyMessage(a: 1) // expected-error{{'unavailableInstancePropertyMessage(a:)' has been replaced by property 'Int.prop': blah}} {{3-37=1.prop}} {{37-43=}}
unavailableClassPropertyMessage() // expected-error{{'unavailableClassPropertyMessage()' has been replaced by property 'Int.prop': blah}} {{3-34=Int.prop}} {{34-36=}}
unavailableGlobalPropertyMessage() // expected-error{{'unavailableGlobalPropertyMessage()' has been replaced by 'global': blah}} {{3-35=global}} {{35-37=}}
deprecatedInstanceProperty(a: 1) // expected-warning {{'deprecatedInstanceProperty(a:)' is deprecated: replaced by property 'Int.prop'}} expected-note{{use 'Int.prop' instead}} {{3-29=1.prop}} {{29-35=}}
deprecatedClassProperty() // expected-warning {{'deprecatedClassProperty()' is deprecated: replaced by property 'Int.prop'}} expected-note{{use 'Int.prop' instead}} {{3-26=Int.prop}} {{26-28=}}
deprecatedGlobalProperty() // expected-warning {{'deprecatedGlobalProperty()' is deprecated: replaced by 'global'}} expected-note{{use 'global' instead}} {{3-27=global}} {{27-29=}}
deprecatedInstancePropertyMessage(a: 1) // expected-warning {{'deprecatedInstancePropertyMessage(a:)' is deprecated: blah}} expected-note{{use 'Int.prop' instead}} {{3-36=1.prop}} {{36-42=}}
deprecatedClassPropertyMessage() // expected-warning {{'deprecatedClassPropertyMessage()' is deprecated: blah}} expected-note{{use 'Int.prop' instead}} {{3-33=Int.prop}} {{33-35=}}
deprecatedGlobalPropertyMessage() // expected-warning {{'deprecatedGlobalPropertyMessage()' is deprecated: blah}} expected-note{{use 'global' instead}} {{3-34=global}} {{34-36=}}
}
@available(*, unavailable, renamed: "setter:Int.prop(self:_:)")
func unavailableSetInstanceProperty(a: Int, b: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(_:self:)")
func unavailableSetInstancePropertyReverse(a: Int, b: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(self:newValue:)")
func unavailableSetInstancePropertyUnlabeled(_ a: Int, _ b: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(newValue:self:)")
func unavailableSetInstancePropertyUnlabeledReverse(_ a: Int, _ b: Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(x:)")
func unavailableSetClassProperty(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "setter:global(_:)")
func unavailableSetGlobalProperty(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "setter:Int.prop(self:_:)")
func unavailableSetInstancePropertyInout(a: inout Int, b: Int) {} // expected-note {{here}}
func testRenameSetters() {
unavailableSetInstanceProperty(a: 1, b: 2) // expected-error{{'unavailableSetInstanceProperty(a:b:)' has been replaced by property 'Int.prop'}} {{3-33=1.prop}} {{33-43= = }} {{44-45=}}
unavailableSetInstancePropertyUnlabeled(1, 2) // expected-error{{'unavailableSetInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-42=1.prop}} {{42-46= = }} {{47-48=}}
unavailableSetInstancePropertyReverse(a: 1, b: 2) // expected-error{{'unavailableSetInstancePropertyReverse(a:b:)' has been replaced by property 'Int.prop'}} {{3-40=2.prop}} {{40-44= = }} {{45-52=}}
unavailableSetInstancePropertyUnlabeledReverse(1, 2) // expected-error{{'unavailableSetInstancePropertyUnlabeledReverse' has been replaced by property 'Int.prop'}} {{3-49=2.prop}} {{49-50= = }} {{51-55=}}
unavailableSetInstanceProperty(a: 1 + 1, b: 2 + 2) // expected-error{{'unavailableSetInstanceProperty(a:b:)' has been replaced by property 'Int.prop'}} {{3-33=(1 + 1).prop}} {{33-47= = }} {{52-53=}}
unavailableSetInstancePropertyUnlabeled(1 + 1, 2 + 2) // expected-error{{'unavailableSetInstancePropertyUnlabeled' has been replaced by property 'Int.prop'}} {{3-42=(1 + 1).prop}} {{42-50= = }} {{55-56=}}
unavailableSetInstancePropertyReverse(a: 1 + 1, b: 2 + 2) // expected-error{{'unavailableSetInstancePropertyReverse(a:b:)' has been replaced by property 'Int.prop'}} {{3-40=(2 + 2).prop}} {{40-44= = }} {{49-60=}}
unavailableSetInstancePropertyUnlabeledReverse(1 + 1, 2 + 2) // expected-error{{'unavailableSetInstancePropertyUnlabeledReverse' has been replaced by property 'Int.prop'}} {{3-49=(2 + 2).prop}} {{49-50= = }} {{55-63=}}
unavailableSetClassProperty(a: 1) // expected-error{{'unavailableSetClassProperty(a:)' has been replaced by property 'Int.prop'}} {{3-30=Int.prop}} {{30-34= = }} {{35-36=}}
unavailableSetGlobalProperty(1) // expected-error{{'unavailableSetGlobalProperty' has been replaced by 'global'}} {{3-31=global}} {{31-32= = }} {{33-34=}}
var x = 0
unavailableSetInstancePropertyInout(a: &x, b: 2) // expected-error{{'unavailableSetInstancePropertyInout(a:b:)' has been replaced by property 'Int.prop'}} {{3-38=x.prop}} {{38-49= = }} {{50-51=}}
}
@available(*, unavailable, renamed: "Int.foo(self:execute:)")
func trailingClosure(_ value: Int, fn: () -> Void) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:bar:execute:)")
func trailingClosureArg(_ value: Int, _ other: Int, fn: () -> Void) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(bar:self:execute:)")
func trailingClosureArg2(_ value: Int, _ other: Int, fn: () -> Void) {} // expected-note {{here}}
func testInstanceTrailingClosure() {
// FIXME: regression in fixit due to noescape-by-default
trailingClosure(0) {} // expected-error {{'trailingClosure(_:fn:)' has been replaced by instance method 'Int.foo(execute:)'}} // FIXME: {{3-18=0.foo}} {{19-20=}}
trailingClosureArg(0, 1) {} // expected-error {{'trailingClosureArg(_:_:fn:)' has been replaced by instance method 'Int.foo(bar:execute:)'}} // FIXME: {{3-21=0.foo}} {{22-25=}} {{25-25=bar: }}
trailingClosureArg2(0, 1) {} // expected-error {{'trailingClosureArg2(_:_:fn:)' has been replaced by instance method 'Int.foo(bar:execute:)'}} // FIXME: {{3-22=1.foo}} {{23-23=bar: }} {{24-27=}}
}
@available(*, unavailable, renamed: "+")
func add(_ value: Int, _ other: Int) {} // expected-note {{here}}
infix operator ***
@available(*, unavailable, renamed: "add")
func ***(value: (), other: ()) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:_:)")
func ***(value: Int, other: Int) {} // expected-note {{here}}
prefix operator ***
@available(*, unavailable, renamed: "add")
prefix func ***(value: Int?) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:)")
prefix func ***(value: Int) {} // expected-note {{here}}
postfix operator ***
@available(*, unavailable, renamed: "add")
postfix func ***(value: Int?) {} // expected-note {{here}}
@available(*, unavailable, renamed: "Int.foo(self:)")
postfix func ***(value: Int) {} // expected-note {{here}}
func testOperators() {
add(0, 1) // expected-error {{'add' has been renamed to '+'}} {{none}}
() *** () // expected-error {{'***' has been renamed to 'add'}} {{none}}
0 *** 1 // expected-error {{'***' has been replaced by instance method 'Int.foo(_:)'}} {{none}}
***nil // expected-error {{'***' has been renamed to 'add'}} {{none}}
***0 // expected-error {{'***' has been replaced by instance method 'Int.foo()'}} {{none}}
nil*** // expected-error {{'***' has been renamed to 'add'}} {{none}}
0*** // expected-error {{'***' has been replaced by instance method 'Int.foo()'}} {{none}}
}
extension Int {
@available(*, unavailable, renamed: "init(other:)")
@discardableResult
static func factory(other: Int) -> Int { return other } // expected-note 2 {{here}}
@available(*, unavailable, renamed: "Int.init(other:)")
@discardableResult
static func factory2(other: Int) -> Int { return other } // expected-note 2 {{here}}
static func testFactoryMethods() {
factory(other: 1) // expected-error {{'factory(other:)' has been replaced by 'init(other:)'}} {{none}}
factory2(other: 1) // expected-error {{'factory2(other:)' has been replaced by 'Int.init(other:)'}} {{5-13=Int}}
}
}
func testFactoryMethods() {
Int.factory(other: 1) // expected-error {{'factory(other:)' has been replaced by 'init(other:)'}} {{6-14=}}
Int.factory2(other: 1) // expected-error {{'factory2(other:)' has been replaced by 'Int.init(other:)'}} {{3-15=Int}}
}
class Base {
@available(*, unavailable)
func bad() {} // expected-note {{here}}
@available(*, unavailable, message: "it was smelly")
func smelly() {} // expected-note {{here}}
@available(*, unavailable, renamed: "new")
func old() {} // expected-note {{here}}
@available(*, unavailable, renamed: "new", message: "it was smelly")
func oldAndSmelly() {} // expected-note {{here}}
@available(*, unavailable)
var badProp: Int { return 0 } // expected-note {{here}}
@available(*, unavailable, message: "it was smelly")
var smellyProp: Int { return 0 } // expected-note {{here}}
@available(*, unavailable, renamed: "new")
var oldProp: Int { return 0 } // expected-note {{here}}
@available(*, unavailable, renamed: "new", message: "it was smelly")
var oldAndSmellyProp: Int { return 0 } // expected-note {{here}}
@available(*, unavailable, renamed: "init")
func nowAnInitializer() {} // expected-note {{here}}
@available(*, unavailable, renamed: "init()")
func nowAnInitializer2() {} // expected-note {{here}}
@available(*, unavailable, renamed: "foo")
init(nowAFunction: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "foo(_:)")
init(nowAFunction2: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableArgNames(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableArgRenamed(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments()")
func unavailableNoArgs() {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:)")
func unavailableSame(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:)")
func unavailableUnnamed(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableUnnamedSame(_ a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:)")
func unavailableNewlyUnnamed(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(a:b:)")
func unavailableMultiSame(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(example:another:)")
func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(_:_:)")
func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "init(shinyNewName:)")
init(unavailableArgNames: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "init(a:)")
init(_ unavailableUnnamed: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "init(_:)")
init(unavailableNewlyUnnamed: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "init(a:b:)")
init(_ unavailableMultiUnnamed: Int, _ b: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "init(_:_:)")
init(unavailableMultiNewlyUnnamed a: Int, b: Int) {} // expected-note{{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:)")
func unavailableTooFew(a: Int, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:b:)")
func unavailableTooMany(a: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "shinyLabeledArguments(x:)")
func unavailableNoArgsTooMany() {} // expected-note {{here}}
@available(*, unavailable, renamed: "Base.shinyLabeledArguments()")
func unavailableHasType() {} // expected-note {{here}}
}
class Sub : Base {
override func bad() {} // expected-error {{cannot override 'bad' which has been marked unavailable}} {{none}}
override func smelly() {} // expected-error {{cannot override 'smelly' which has been marked unavailable: it was smelly}} {{none}}
override func old() {} // expected-error {{'old()' has been renamed to 'new'}} {{17-20=new}}
override func oldAndSmelly() {} // expected-error {{'oldAndSmelly()' has been renamed to 'new': it was smelly}} {{17-29=new}}
override var badProp: Int { return 0 } // expected-error {{cannot override 'badProp' which has been marked unavailable}} {{none}}
override var smellyProp: Int { return 0 } // expected-error {{cannot override 'smellyProp' which has been marked unavailable: it was smelly}} {{none}}
override var oldProp: Int { return 0 } // expected-error {{'oldProp' has been renamed to 'new'}} {{16-23=new}}
override var oldAndSmellyProp: Int { return 0 } // expected-error {{'oldAndSmellyProp' has been renamed to 'new': it was smelly}} {{16-32=new}}
override func nowAnInitializer() {} // expected-error {{'nowAnInitializer()' has been replaced by 'init'}} {{none}}
override func nowAnInitializer2() {} // expected-error {{'nowAnInitializer2()' has been replaced by 'init()'}} {{none}}
override init(nowAFunction: Int) {} // expected-error {{'init(nowAFunction:)' has been renamed to 'foo'}} {{none}}
override init(nowAFunction2: Int) {} // expected-error {{'init(nowAFunction2:)' has been renamed to 'foo(_:)'}} {{none}}
override func unavailableArgNames(a: Int) {} // expected-error {{'unavailableArgNames(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-36=shinyLabeledArguments}} {{37-37=example }}
override func unavailableArgRenamed(a param: Int) {} // expected-error {{'unavailableArgRenamed(a:)' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-38=shinyLabeledArguments}} {{39-40=example}}
override func unavailableNoArgs() {} // expected-error {{'unavailableNoArgs()' has been renamed to 'shinyLabeledArguments()'}} {{17-34=shinyLabeledArguments}}
override func unavailableSame(a: Int) {} // expected-error {{'unavailableSame(a:)' has been renamed to 'shinyLabeledArguments(a:)'}} {{17-32=shinyLabeledArguments}}
override func unavailableUnnamed(_ a: Int) {} // expected-error {{'unavailableUnnamed' has been renamed to 'shinyLabeledArguments(example:)'}} {{17-35=shinyLabeledArguments}} {{36-37=example}}
override func unavailableUnnamedSame(_ a: Int) {} // expected-error {{'unavailableUnnamedSame' has been renamed to 'shinyLabeledArguments(_:)'}} {{17-39=shinyLabeledArguments}}
override func unavailableNewlyUnnamed(a: Int) {} // expected-error {{'unavailableNewlyUnnamed(a:)' has been renamed to 'shinyLabeledArguments(_:)'}} {{17-40=shinyLabeledArguments}} {{41-41=_ }}
override func unavailableMultiSame(a: Int, b: Int) {} // expected-error {{'unavailableMultiSame(a:b:)' has been renamed to 'shinyLabeledArguments(a:b:)'}} {{17-37=shinyLabeledArguments}}
override func unavailableMultiUnnamed(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamed' has been renamed to 'shinyLabeledArguments(example:another:)'}} {{17-40=shinyLabeledArguments}} {{41-42=example}} {{51-52=another}}
override func unavailableMultiUnnamedSame(_ a: Int, _ b: Int) {} // expected-error {{'unavailableMultiUnnamedSame' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{17-44=shinyLabeledArguments}}
override func unavailableMultiNewlyUnnamed(a: Int, b: Int) {} // expected-error {{'unavailableMultiNewlyUnnamed(a:b:)' has been renamed to 'shinyLabeledArguments(_:_:)'}} {{17-45=shinyLabeledArguments}} {{46-46=_ }} {{54-54=_ }}
override init(unavailableArgNames: Int) {} // expected-error {{'init(unavailableArgNames:)' has been renamed to 'init(shinyNewName:)'}} {{17-17=shinyNewName }}
override init(_ unavailableUnnamed: Int) {} // expected-error {{'init' has been renamed to 'init(a:)'}} {{17-18=a}}
override init(unavailableNewlyUnnamed: Int) {} // expected-error {{'init(unavailableNewlyUnnamed:)' has been renamed to 'init(_:)'}} {{17-17=_ }}
override init(_ unavailableMultiUnnamed: Int, _ b: Int) {} // expected-error {{'init' has been renamed to 'init(a:b:)'}} {{17-18=a}} {{49-51=}}
override init(unavailableMultiNewlyUnnamed a: Int, b: Int) {} // expected-error {{'init(unavailableMultiNewlyUnnamed:b:)' has been renamed to 'init(_:_:)'}} {{17-45=_}} {{54-54=_ }}
override func unavailableTooFew(a: Int, b: Int) {} // expected-error {{'unavailableTooFew(a:b:)' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}}
override func unavailableTooMany(a: Int) {} // expected-error {{'unavailableTooMany(a:)' has been renamed to 'shinyLabeledArguments(x:b:)'}} {{none}}
override func unavailableNoArgsTooMany() {} // expected-error {{'unavailableNoArgsTooMany()' has been renamed to 'shinyLabeledArguments(x:)'}} {{none}}
override func unavailableHasType() {} // expected-error {{'unavailableHasType()' has been replaced by 'Base.shinyLabeledArguments()'}} {{none}}
}
// U: Unnamed, L: Labeled
@available(*, unavailable, renamed: "after(fn:)")
func closure_U_L(_ x: () -> Int) {} // expected-note 3 {{here}}
@available(*, unavailable, renamed: "after(fn:)")
func closure_L_L(x: () -> Int) {} // expected-note 3 {{here}}
@available(*, unavailable, renamed: "after(_:)")
func closure_L_U(x: () -> Int) {} // expected-note 3 {{here}}
@available(*, unavailable, renamed: "after(arg:fn:)")
func closure_UU_LL(_ x: Int, _ y: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:fn:)")
func closure_LU_LL(x: Int, _ y: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:fn:)")
func closure_LL_LL(x: Int, y: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:fn:)")
func closure_UU_LL_ne(_ x: Int, _ y: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:_:)")
func closure_UU_LU(_ x: Int, _ closure: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:_:)")
func closure_LU_LU(x: Int, _ closure: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:_:)")
func closure_LL_LU(x: Int, y: () -> Int) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(arg:_:)")
func closure_UU_LU_ne(_ x: Int, _ y: () -> Int) {} // expected-note 2 {{here}}
func testTrailingClosure() {
closure_U_L { 0 } // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}}
closure_U_L() { 0 } // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}}
closure_U_L({ 0 }) // expected-error {{'closure_U_L' has been renamed to 'after(fn:)'}} {{3-14=after}} {{15-15=fn: }} {{none}}
closure_L_L { 0 } // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}}
closure_L_L() { 0 } // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{none}}
closure_L_L(x: { 0 }) // expected-error {{'closure_L_L(x:)' has been renamed to 'after(fn:)'}} {{3-14=after}} {{15-16=fn}} {{none}}
closure_L_U { 0 } // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{none}}
closure_L_U() { 0 } // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{none}}
closure_L_U(x: { 0 }) // expected-error {{'closure_L_U(x:)' has been renamed to 'after(_:)'}} {{3-14=after}} {{15-18=}} {{none}}
closure_UU_LL(0) { 0 } // expected-error {{'closure_UU_LL' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-17=arg: }} {{none}}
closure_UU_LL(0, { 0 }) // expected-error {{'closure_UU_LL' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-17=arg: }} {{20-20=fn: }} {{none}}
closure_LU_LL(x: 0) { 0 } // expected-error {{'closure_LU_LL(x:_:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{none}}
closure_LU_LL(x: 0, { 0 }) // expected-error {{'closure_LU_LL(x:_:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{23-23=fn: }} {{none}}
closure_LL_LL(x: 1) { 1 } // expected-error {{'closure_LL_LL(x:y:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{none}}
closure_LL_LL(x: 1, y: { 0 }) // expected-error {{'closure_LL_LL(x:y:)' has been renamed to 'after(arg:fn:)'}} {{3-16=after}} {{17-18=arg}} {{23-24=fn}} {{none}}
closure_UU_LL_ne(1) { 1 } // expected-error {{'closure_UU_LL_ne' has been renamed to 'after(arg:fn:)'}} {{3-19=after}} {{20-20=arg: }} {{none}}
closure_UU_LL_ne(1, { 0 }) // expected-error {{'closure_UU_LL_ne' has been renamed to 'after(arg:fn:)'}} {{3-19=after}} {{20-20=arg: }} {{23-23=fn: }} {{none}}
closure_UU_LU(0) { 0 } // expected-error {{'closure_UU_LU' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-17=arg: }} {{none}}
closure_UU_LU(0, { 0 }) // expected-error {{'closure_UU_LU' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-17=arg: }} {{none}}
closure_LU_LU(x: 0) { 0 } // expected-error {{'closure_LU_LU(x:_:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}}
closure_LU_LU(x: 0, { 0 }) // expected-error {{'closure_LU_LU(x:_:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}}
closure_LL_LU(x: 1) { 1 } // expected-error {{'closure_LL_LU(x:y:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{none}}
closure_LL_LU(x: 1, y: { 0 }) // expected-error {{'closure_LL_LU(x:y:)' has been renamed to 'after(arg:_:)'}} {{3-16=after}} {{17-18=arg}} {{23-26=}} {{none}}
closure_UU_LU_ne(1) { 1 } // expected-error {{'closure_UU_LU_ne' has been renamed to 'after(arg:_:)'}} {{3-19=after}} {{20-20=arg: }} {{none}}
closure_UU_LU_ne(1, { 0 }) // expected-error {{'closure_UU_LU_ne' has been renamed to 'after(arg:_:)'}} {{3-19=after}} {{20-20=arg: }} {{none}}
}
@available(*, unavailable, renamed: "after(x:)")
func defaultUnnamed(_ a: Int = 1) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(x:y:)")
func defaultBeforeRequired(a: Int = 1, b: Int) {} // expected-note {{here}}
@available(*, unavailable, renamed: "after(x:y:z:)")
func defaultPlusTrailingClosure(a: Int = 1, b: Int = 2, c: () -> Void) {} // expected-note 3 {{here}}
func testDefaults() {
defaultUnnamed() // expected-error {{'defaultUnnamed' has been renamed to 'after(x:)'}} {{3-17=after}} {{none}}
defaultUnnamed(1) // expected-error {{'defaultUnnamed' has been renamed to 'after(x:)'}} {{3-17=after}} {{18-18=x: }} {{none}}
defaultBeforeRequired(b: 5) // expected-error {{'defaultBeforeRequired(a:b:)' has been renamed to 'after(x:y:)'}} {{3-24=after}} {{25-26=y}} {{none}}
defaultPlusTrailingClosure {} // expected-error {{'defaultPlusTrailingClosure(a:b:c:)' has been renamed to 'after(x:y:z:)'}} {{3-29=after}} {{none}}
defaultPlusTrailingClosure(c: {}) // expected-error {{'defaultPlusTrailingClosure(a:b:c:)' has been renamed to 'after(x:y:z:)'}} {{3-29=after}} {{30-31=z}} {{none}}
defaultPlusTrailingClosure(a: 1) {} // expected-error {{'defaultPlusTrailingClosure(a:b:c:)' has been renamed to 'after(x:y:z:)'}} {{3-29=after}} {{30-31=x}} {{none}}
}
@available(*, unavailable, renamed: "after(x:y:)")
func variadic1(a: Int ..., b: Int = 0) {} // expected-note 2 {{here}}
@available(*, unavailable, renamed: "after(x:y:)")
func variadic2(a: Int, _ b: Int ...) {} // expected-note {{here}}
@available(*, unavailable, renamed: "after(x:_:y:z:)")
func variadic3(_ a: Int, b: Int ..., c: String = "", d: String) {} // expected-note 2 {{here}}
func testVariadic() {
variadic1(a: 1, 2) // expected-error {{'variadic1(a:b:)' has been renamed to 'after(x:y:)'}} {{3-12=after}} {{13-14=x}} {{none}}
variadic1(a: 1, 2, b: 3) // expected-error {{'variadic1(a:b:)' has been renamed to 'after(x:y:)'}} {{3-12=after}} {{13-14=x}} {{22-23=y}} {{none}}
variadic2(a: 1, 2, 3) // expected-error {{'variadic2(a:_:)' has been renamed to 'after(x:y:)'}} {{3-12=after}} {{13-14=x}} {{19-19=y: }} {{none}}
variadic3(1, b: 2, 3, d: "test") // expected-error {{'variadic3(_:b:c:d:)' has been renamed to 'after(x:_:y:z:)'}} {{3-12=after}} {{13-13=x: }} {{16-19=}} {{25-26=z}} {{none}}
variadic3(1, d:"test") // expected-error {{'variadic3(_:b:c:d:)' has been renamed to 'after(x:_:y:z:)'}} {{3-12=after}} {{13-13=x: }} {{16-17=z}} {{none}}
}
enum E_32526620 {
case foo
case bar
func set() {}
}
@available(*, unavailable, renamed: "E_32526620.set(self:)")
func rdar32526620_1(a: E_32526620) {} // expected-note {{here}}
rdar32526620_1(a: .foo)
// expected-error@-1 {{'rdar32526620_1(a:)' has been replaced by instance method 'E_32526620.set()'}} {{1-15=E_32526620.foo.set}} {{16-23=}}
@available(*, unavailable, renamed: "E_32526620.set(a:self:)")
func rdar32526620_2(a: Int, b: E_32526620) {} // expected-note {{here}}
rdar32526620_2(a: 42, b: .bar)
// expected-error@-1 {{'rdar32526620_2(a:b:)' has been replaced by instance method 'E_32526620.set(a:)'}} {{1-15=E_32526620.bar.set}} {{21-30=}}
@available(*, unavailable, renamed: "E_32526620.set(a:self:c:)")
func rdar32526620_3(a: Int, b: E_32526620, c: String) {} // expected-note {{here}}
rdar32526620_3(a: 42, b: .bar, c: "question")
// expected-error@-1 {{'rdar32526620_3(a:b:c:)' has been replaced by instance method 'E_32526620.set(a:c:)'}} {{1-15=E_32526620.bar.set}} {{23-32=}}
@available(*, unavailable) // expected-warning {{'@available' without an OS is ignored on extensions; apply the attribute to each member instead}} {{1-28=}}
extension DummyType {}
@available(*, deprecated) // expected-warning {{'@available' without an OS is ignored on extensions; apply the attribute to each member instead}} {{1-27=}}
extension DummyType {}
var deprecatedGetter: Int {
@available(*, deprecated) get { return 0 }
set {}
}
var deprecatedGetterOnly: Int {
@available(*, deprecated) get { return 0 }
}
var deprecatedSetter: Int {
get { return 0 }
@available(*, deprecated) set {}
}
var deprecatedBoth: Int {
@available(*, deprecated) get { return 0 }
@available(*, deprecated) set {}
}
var deprecatedMessage: Int {
@available(*, deprecated, message: "bad getter") get { return 0 }
@available(*, deprecated, message: "bad setter") set {}
}
var deprecatedRename: Int {
@available(*, deprecated, renamed: "betterThing()") get { return 0 }
@available(*, deprecated, renamed: "setBetterThing(_:)") set {}
}
@available(*, deprecated, message: "bad variable")
var deprecatedProperty: Int {
@available(*, deprecated, message: "bad getter") get { return 0 }
@available(*, deprecated, message: "bad setter") set {}
}
_ = deprecatedGetter // expected-warning {{getter for 'deprecatedGetter' is deprecated}} {{none}}
deprecatedGetter = 0
deprecatedGetter += 1 // expected-warning {{getter for 'deprecatedGetter' is deprecated}} {{none}}
_ = deprecatedGetterOnly // expected-warning {{getter for 'deprecatedGetterOnly' is deprecated}} {{none}}
_ = deprecatedSetter
deprecatedSetter = 0 // expected-warning {{setter for 'deprecatedSetter' is deprecated}} {{none}}
deprecatedSetter += 1 // expected-warning {{setter for 'deprecatedSetter' is deprecated}} {{none}}
_ = deprecatedBoth // expected-warning {{getter for 'deprecatedBoth' is deprecated}} {{none}}
deprecatedBoth = 0 // expected-warning {{setter for 'deprecatedBoth' is deprecated}} {{none}}
deprecatedBoth += 1 // expected-warning {{getter for 'deprecatedBoth' is deprecated}} {{none}} expected-warning {{setter for 'deprecatedBoth' is deprecated}} {{none}}
_ = deprecatedMessage // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}}
deprecatedMessage = 0 // expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
deprecatedMessage += 1 // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}} expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
_ = deprecatedRename // expected-warning {{getter for 'deprecatedRename' is deprecated: renamed to 'betterThing()'}} {{none}}
deprecatedRename = 0 // expected-warning {{setter for 'deprecatedRename' is deprecated: renamed to 'setBetterThing(_:)'}} {{none}}
deprecatedRename += 1 // expected-warning {{getter for 'deprecatedRename' is deprecated: renamed to 'betterThing()'}} {{none}} expected-warning {{setter for 'deprecatedRename' is deprecated: renamed to 'setBetterThing(_:)'}} {{none}}
_ = deprecatedProperty // expected-warning {{'deprecatedProperty' is deprecated: bad variable}} {{none}}
deprecatedProperty = 0 // expected-warning {{'deprecatedProperty' is deprecated: bad variable}} {{none}}
deprecatedProperty += 1 // expected-warning {{'deprecatedProperty' is deprecated: bad variable}} {{none}}
var unavailableGetter: Int {
@available(*, unavailable) get { return 0 } // expected-note * {{here}}
set {}
}
var unavailableGetterOnly: Int {
@available(*, unavailable) get { return 0 } // expected-note * {{here}}
}
var unavailableSetter: Int {
get { return 0 }
@available(*, unavailable) set {} // expected-note * {{here}}
}
var unavailableBoth: Int {
@available(*, unavailable) get { return 0 } // expected-note * {{here}}
@available(*, unavailable) set {} // expected-note * {{here}}
}
var unavailableMessage: Int {
@available(*, unavailable, message: "bad getter") get { return 0 } // expected-note * {{here}}
@available(*, unavailable, message: "bad setter") set {} // expected-note * {{here}}
}
var unavailableRename: Int {
@available(*, unavailable, renamed: "betterThing()") get { return 0 } // expected-note * {{here}}
@available(*, unavailable, renamed: "setBetterThing(_:)") set {} // expected-note * {{here}}
}
@available(*, unavailable, message: "bad variable")
var unavailableProperty: Int { // expected-note * {{here}}
@available(*, unavailable, message: "bad getter") get { return 0 }
@available(*, unavailable, message: "bad setter") set {}
}
_ = unavailableGetter // expected-error {{getter for 'unavailableGetter' is unavailable}} {{none}}
unavailableGetter = 0
unavailableGetter += 1 // expected-error {{getter for 'unavailableGetter' is unavailable}} {{none}}
_ = unavailableGetterOnly // expected-error {{getter for 'unavailableGetterOnly' is unavailable}} {{none}}
_ = unavailableSetter
unavailableSetter = 0 // expected-error {{setter for 'unavailableSetter' is unavailable}} {{none}}
unavailableSetter += 1 // expected-error {{setter for 'unavailableSetter' is unavailable}} {{none}}
_ = unavailableBoth // expected-error {{getter for 'unavailableBoth' is unavailable}} {{none}}
unavailableBoth = 0 // expected-error {{setter for 'unavailableBoth' is unavailable}} {{none}}
unavailableBoth += 1 // expected-error {{getter for 'unavailableBoth' is unavailable}} {{none}} expected-error {{setter for 'unavailableBoth' is unavailable}} {{none}}
_ = unavailableMessage // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}}
unavailableMessage = 0 // expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
unavailableMessage += 1 // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}} expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
_ = unavailableRename // expected-error {{getter for 'unavailableRename' has been renamed to 'betterThing()'}} {{none}}
unavailableRename = 0 // expected-error {{setter for 'unavailableRename' has been renamed to 'setBetterThing(_:)'}} {{none}}
unavailableRename += 1 // expected-error {{getter for 'unavailableRename' has been renamed to 'betterThing()'}} {{none}} expected-error {{setter for 'unavailableRename' has been renamed to 'setBetterThing(_:)'}} {{none}}
_ = unavailableProperty // expected-error {{'unavailableProperty' is unavailable: bad variable}} {{none}}
unavailableProperty = 0 // expected-error {{'unavailableProperty' is unavailable: bad variable}} {{none}}
unavailableProperty += 1 // expected-error {{'unavailableProperty' is unavailable: bad variable}} {{none}}
struct DeprecatedAccessors {
var deprecatedMessage: Int {
@available(*, deprecated, message: "bad getter") get { return 0 }
@available(*, deprecated, message: "bad setter") set {}
}
static var staticDeprecated: Int {
@available(*, deprecated, message: "bad getter") get { return 0 }
@available(*, deprecated, message: "bad setter") set {}
}
@available(*, deprecated, message: "bad property")
var deprecatedProperty: Int {
@available(*, deprecated, message: "bad getter") get { return 0 }
@available(*, deprecated, message: "bad setter") set {}
}
subscript(_: Int) -> Int {
@available(*, deprecated, message: "bad subscript getter") get { return 0 }
@available(*, deprecated, message: "bad subscript setter") set {}
}
@available(*, deprecated, message: "bad subscript!")
subscript(alsoDeprecated _: Int) -> Int {
@available(*, deprecated, message: "bad subscript getter") get { return 0 }
@available(*, deprecated, message: "bad subscript setter") set {}
}
mutating func testAccessors(other: inout DeprecatedAccessors) {
_ = deprecatedMessage // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}}
deprecatedMessage = 0 // expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
deprecatedMessage += 1 // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}} expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
_ = other.deprecatedMessage // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}}
other.deprecatedMessage = 0 // expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
other.deprecatedMessage += 1 // expected-warning {{getter for 'deprecatedMessage' is deprecated: bad getter}} {{none}} expected-warning {{setter for 'deprecatedMessage' is deprecated: bad setter}} {{none}}
_ = other.deprecatedProperty // expected-warning {{'deprecatedProperty' is deprecated: bad property}} {{none}}
other.deprecatedProperty = 0 // expected-warning {{'deprecatedProperty' is deprecated: bad property}} {{none}}
other.deprecatedProperty += 1 // expected-warning {{'deprecatedProperty' is deprecated: bad property}} {{none}}
_ = DeprecatedAccessors.staticDeprecated // expected-warning {{getter for 'staticDeprecated' is deprecated: bad getter}} {{none}}
DeprecatedAccessors.staticDeprecated = 0 // expected-warning {{setter for 'staticDeprecated' is deprecated: bad setter}} {{none}}
DeprecatedAccessors.staticDeprecated += 1 // expected-warning {{getter for 'staticDeprecated' is deprecated: bad getter}} {{none}} expected-warning {{setter for 'staticDeprecated' is deprecated: bad setter}} {{none}}
_ = other[0] // expected-warning {{getter for 'subscript' is deprecated: bad subscript getter}} {{none}}
other[0] = 0 // expected-warning {{setter for 'subscript' is deprecated: bad subscript setter}} {{none}}
other[0] += 1 // expected-warning {{getter for 'subscript' is deprecated: bad subscript getter}} {{none}} expected-warning {{setter for 'subscript' is deprecated: bad subscript setter}} {{none}}
_ = other[alsoDeprecated: 0] // expected-warning {{'subscript(alsoDeprecated:)' is deprecated: bad subscript!}} {{none}}
other[alsoDeprecated: 0] = 0 // expected-warning {{'subscript(alsoDeprecated:)' is deprecated: bad subscript!}} {{none}}
other[alsoDeprecated: 0] += 1 // expected-warning {{'subscript(alsoDeprecated:)' is deprecated: bad subscript!}} {{none}}
}
}
struct UnavailableAccessors {
var unavailableMessage: Int {
@available(*, unavailable, message: "bad getter") get { return 0 } // expected-note * {{here}}
@available(*, unavailable, message: "bad setter") set {} // expected-note * {{here}}
}
static var staticUnavailable: Int {
@available(*, unavailable, message: "bad getter") get { return 0 } // expected-note * {{here}}
@available(*, unavailable, message: "bad setter") set {} // expected-note * {{here}}
}
@available(*, unavailable, message: "bad property")
var unavailableProperty: Int { // expected-note * {{here}}
@available(*, unavailable, message: "bad getter") get { return 0 }
@available(*, unavailable, message: "bad setter") set {}
}
subscript(_: Int) -> Int {
@available(*, unavailable, message: "bad subscript getter") get { return 0 } // expected-note * {{here}}
@available(*, unavailable, message: "bad subscript setter") set {} // expected-note * {{here}}
}
@available(*, unavailable, message: "bad subscript!")
subscript(alsoUnavailable _: Int) -> Int { // expected-note * {{here}}
@available(*, unavailable, message: "bad subscript getter") get { return 0 }
@available(*, unavailable, message: "bad subscript setter") set {}
}
mutating func testAccessors(other: inout UnavailableAccessors) {
_ = unavailableMessage // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}}
unavailableMessage = 0 // expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
unavailableMessage += 1 // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}} expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
_ = other.unavailableMessage // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}}
other.unavailableMessage = 0 // expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
other.unavailableMessage += 1 // expected-error {{getter for 'unavailableMessage' is unavailable: bad getter}} {{none}} expected-error {{setter for 'unavailableMessage' is unavailable: bad setter}} {{none}}
_ = other.unavailableProperty // expected-error {{'unavailableProperty' is unavailable: bad property}} {{none}}
other.unavailableProperty = 0 // expected-error {{'unavailableProperty' is unavailable: bad property}} {{none}}
other.unavailableProperty += 1 // expected-error {{'unavailableProperty' is unavailable: bad property}} {{none}}
_ = UnavailableAccessors.staticUnavailable // expected-error {{getter for 'staticUnavailable' is unavailable: bad getter}} {{none}}
UnavailableAccessors.staticUnavailable = 0 // expected-error {{setter for 'staticUnavailable' is unavailable: bad setter}} {{none}}
UnavailableAccessors.staticUnavailable += 1 // expected-error {{getter for 'staticUnavailable' is unavailable: bad getter}} {{none}} expected-error {{setter for 'staticUnavailable' is unavailable: bad setter}} {{none}}
_ = other[0] // expected-error {{getter for 'subscript' is unavailable: bad subscript getter}} {{none}}
other[0] = 0 // expected-error {{setter for 'subscript' is unavailable: bad subscript setter}} {{none}}
other[0] += 1 // expected-error {{getter for 'subscript' is unavailable: bad subscript getter}} {{none}} expected-error {{setter for 'subscript' is unavailable: bad subscript setter}} {{none}}
_ = other[alsoUnavailable: 0] // expected-error {{'subscript(alsoUnavailable:)' is unavailable: bad subscript!}} {{none}}
other[alsoUnavailable: 0] = 0 // expected-error {{'subscript(alsoUnavailable:)' is unavailable: bad subscript!}} {{none}}
other[alsoUnavailable: 0] += 1 // expected-error {{'subscript(alsoUnavailable:)' is unavailable: bad subscript!}} {{none}}
}
}
| apache-2.0 | b01533144ada82d90e116ba895ea110e | 63.646095 | 303 | 0.695128 | 3.924941 | false | false | false | false |
manfengjun/KYMart | Section/Product/Detail/View/KYProductInfoTVCell.swift | 1 | 3958 | //
// KYProductInfoTVCell.swift
// KYMart
//
// Created by jun on 2017/6/8.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
class KYProductInfoTVCell: UITableViewCell {
@IBOutlet weak var scrollCircleView: SDCycleScrollView!
@IBOutlet weak var productInfoL: UILabel!
@IBOutlet weak var shopPriceL: UILabel!
@IBOutlet weak var marketPriceL: UILabel!
@IBOutlet weak var discountL: UILabel!
@IBOutlet weak var commentL: UILabel!
@IBOutlet weak var buyCount: UILabel!
@IBOutlet weak var shareView: UIView!
@IBOutlet weak var selectView: UIView!
@IBOutlet weak var selectL: UILabel!
@IBOutlet weak var productTypeIV: UIImageView!
//闭包类型
var replyColsure:((Int)->())?
var model:KYGoodInfoModel?{
didSet {
if let array = model?.gallery {
var images:[String] = []
for item in array {
images.append(item.image_url)
}
scrollCircleView.imageURLStringsGroup = images
}
if let text = model?.goods.goods_name {
productInfoL.text = text
}
if let text = SingleManager.instance.productBuyInfoModel?.good_buy_price {
shopPriceL.text = "¥\(text)"
}
if let shopPricetext = model?.goods.shop_price {
if let marketPricetext = model?.goods.market_price {
marketPriceL.text = "价格:¥\(marketPricetext)"
let shopprice = NSString(string: shopPricetext).floatValue
let marketprice = NSString(string: marketPricetext).floatValue
discountL.text = String(format: "折扣:%.1f折", shopprice/marketprice*10)
}
}
if let array = model?.comment {
commentL.text = "\(array.count)人评价"
}
if let text = model?.goods.sales_sum {
buyCount.text = "\(text)人已付款"
}
if let text = SingleManager.instance.productBuyInfoModel?.good_select_info {
selectL.text = text
}
if let text = model?.goods.ky_type {
productTypeIV.sd_setImage(with: URL(string: "http://www.kymart.cn/public/app/goods/\(text).png"))
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
selectView.isUserInteractionEnabled = true
scrollCircleView.currentPageDotColor = BAR_TINTCOLOR
scrollCircleView.pageDotColor = UIColor.hexStringColor(hex: "#666666")
// let shareTap = UITapGestureRecognizer(target: self, action: #selector(tapAction(guesture:)))
// shareView.addGestureRecognizer(shareTap)
let selectTap = UITapGestureRecognizer(target: self, action: #selector(tapAction(guesture:)))
selectView.addGestureRecognizer(selectTap)
//接受通知监听
NotificationCenter.default.addObserver(self, selector:#selector(selectProperty),name: SelectProductProperty, object: nil)
}
//通知处理函数
func selectProperty(){
if let text = SingleManager.instance.productBuyInfoModel?.good_buy_price{
shopPriceL.text = "¥\(text)"
}
if let text = SingleManager.instance.productBuyInfoModel?.good_select_info {
selectL.text = text
}
}
func tapAction(guesture:UITapGestureRecognizer) {
if (guesture.view?.isEqual(shareView))! {
if let colsure = replyColsure {
colsure(1)
}
}
else
{
if let colsure = replyColsure {
colsure(2)
}
}
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 363b99484ad97f95e653ed09f0669952 | 35.35514 | 129 | 0.589717 | 4.455899 | false | false | false | false |
Reggian/IOS-Pods-DFU-Library | iOSDFULibrary/Classes/Implementation/SecureDFU/Characteristics/SecureDFUControlPoint.swift | 1 | 18644 | /*
* Copyright (c) 2016, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import CoreBluetooth
internal typealias SecureDFUProgressCallback = (_ bytesReceived:Int) -> Void
internal enum SecureDFUOpCode : UInt8 {
case createObject = 0x01
case setPRNValue = 0x02
case calculateChecksum = 0x03
case execute = 0x04
case readError = 0x05
case readObjectInfo = 0x06
case responseCode = 0x60
var code:UInt8 {
return rawValue
}
var description: String{
switch self {
case .createObject: return "Create Object"
case .setPRNValue: return "Set PRN Value"
case .calculateChecksum: return "Calculate Checksum"
case .execute: return "Execute"
case .readError: return "Read Error"
case .readObjectInfo: return "Read Object Info"
case .responseCode: return "Response Code"
}
}
}
internal enum SecureDFUProcedureType : UInt8 {
case command = 0x01
case data = 0x02
var description: String{
switch self{
case .command: return "Command"
case .data: return "Data"
}
}
}
internal enum SecureDFURequest {
case createData(size : UInt32)
case createCommand(size : UInt32)
case readError()
case readObjectInfoCommand()
case readObjectInfoData()
case setPacketReceiptNotification(value : UInt16)
case calculateChecksumCommand()
case executeCommand()
var data : Data {
switch self {
case .createData(let aSize):
//Split to UInt8
let byteArray = stride(from: 24, through: 0, by: -8).map {
UInt8(truncatingBitPattern: aSize >> UInt32($0))
}
//Size is converted to Little Endian (0123 -> 3210)
let bytes:[UInt8] = [UInt8(SecureDFUOpCode.createObject.code), UInt8(SecureDFUProcedureType.data.rawValue), byteArray[3], byteArray[2], byteArray[1], byteArray[0]]
return Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count)
case .createCommand(let aSize):
//Split to UInt8
let byteArray = stride(from: 24, through: 0, by: -8).map {
UInt8(truncatingBitPattern: aSize >> UInt32($0))
}
//Size is converted to Little Endian (0123 -> 3210)
let bytes:[UInt8] = [UInt8(SecureDFUOpCode.createObject.code), UInt8(SecureDFUProcedureType.command.rawValue), byteArray[3], byteArray[2], byteArray[1], byteArray[0]]
return Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count)
case .readError():
let bytes:[UInt8] = [SecureDFUOpCode.readError.code]
return Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count)
case .readObjectInfoCommand():
let bytes:[UInt8] = [SecureDFUOpCode.readObjectInfo.code, SecureDFUProcedureType.command.rawValue]
return Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count)
case .readObjectInfoData():
let bytes:[UInt8] = [SecureDFUOpCode.readObjectInfo.code, SecureDFUProcedureType.data.rawValue]
return Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count)
case .setPacketReceiptNotification(let aSize):
let byteArary:[UInt8] = [UInt8(aSize>>8), UInt8(aSize & 0x00FF)]
let bytes:[UInt8] = [UInt8(SecureDFUOpCode.setPRNValue.code), byteArary[1], byteArary[0]]
return Data(bytes: UnsafePointer<UInt8>(bytes), count: bytes.count)
case .calculateChecksumCommand():
let byteArray:[UInt8] = [UInt8(SecureDFUOpCode.calculateChecksum.code)]
return Data(bytes: UnsafePointer<UInt8>(byteArray), count: byteArray.count)
case .executeCommand():
let byteArray:[UInt8] = [UInt8(SecureDFUOpCode.execute.code)]
return Data(bytes: UnsafePointer<UInt8>(byteArray), count: byteArray.count)
}
}
var description : String {
switch self {
case .createData(let size):
return "Create object data with size : \(size)"
case .createCommand(let size):
return "Create object command with size: \(size)"
case .readObjectInfoCommand():
return "Read object information command"
case .readObjectInfoData():
return "Read object information data"
case .setPacketReceiptNotification(let size):
return "Packet Receipt Notification command with value: \(size)"
case .calculateChecksumCommand():
return "Calculate checksum for last object"
case .executeCommand():
return "Execute last object command"
case .readError():
return "Read Extended error command"
}
}
}
internal enum SecureDFUResultCode : UInt8 {
case invalidCode = 0x0
case success = 0x01
case opCodeNotSupported = 0x02
case invalidParameter = 0x03
case insufficientResources = 0x04
case invalidObjcet = 0x05
case signatureMismatch = 0x06
case unsupportedType = 0x07
case operationNotpermitted = 0x08
case operationFailed = 0x0A
case extendedError = 0x0B
var description:String {
switch self {
case .invalidCode: return "Invalid code"
case .success: return "Success"
case .opCodeNotSupported: return "Operation not supported"
case .invalidParameter: return "Invalid parameter"
case .insufficientResources: return "Insufficient resources"
case .invalidObjcet: return "Invalid object"
case .signatureMismatch: return "Signature mismatch"
case .operationNotpermitted: return "Operation not permitted"
case .unsupportedType: return "Unsupported type"
case .operationFailed: return "Operation failed"
case .extendedError: return "Extended error"
}
}
var code:UInt8 {
return rawValue
}
}
internal struct SecureDFUResponse {
let opCode:SecureDFUOpCode?
let requestOpCode:SecureDFUOpCode?
let status:SecureDFUResultCode?
var responseData : Data?
init?(_ data:Data) {
var opCode :UInt8 = 0
var requestOpCode :UInt8 = 0
var status :UInt8 = 0
(data as NSData).getBytes(&opCode, range: NSRange(location: 0, length: 1))
(data as NSData).getBytes(&requestOpCode, range: NSRange(location: 1, length: 1))
(data as NSData).getBytes(&status, range: NSRange(location: 2, length: 1))
self.opCode = SecureDFUOpCode(rawValue: opCode)
self.requestOpCode = SecureDFUOpCode(rawValue: requestOpCode)
self.status = SecureDFUResultCode(rawValue: status)
if data.count > 3 {
self.responseData = data.subdata(in: 3..<data.count)
}else{
self.responseData = nil
}
if self.opCode != SecureDFUOpCode.responseCode || self.requestOpCode == nil || self.status == nil {
return nil
}
}
var description:String {
return "Response (Op Code = \(requestOpCode!.description), Status = \(status!.description))"
}
}
internal struct SecureDFUPacketReceiptNotification {
let opCode : SecureDFUOpCode?
let requestOpCode : SecureDFUOpCode?
let resultCode : SecureDFUResultCode?
let offset : Int
let crc : UInt32
init?(_ data:Data) {
var opCode : UInt8 = 0
var requestOpCode : UInt8 = 0
var resultCode : UInt8 = 0
(data as NSData).getBytes(&opCode, range: NSRange(location: 0, length: 1))
(data as NSData).getBytes(&requestOpCode, range: NSRange(location: 1, length: 1))
(data as NSData).getBytes(&resultCode, range: NSRange(location: 2, length: 1))
self.opCode = SecureDFUOpCode(rawValue: opCode)
self.requestOpCode = SecureDFUOpCode(rawValue: requestOpCode)
self.resultCode = SecureDFUResultCode(rawValue: resultCode)
if self.opCode != SecureDFUOpCode.responseCode {
print("wrong opcode \(self.opCode?.description)")
return nil
}
if self.requestOpCode != SecureDFUOpCode.calculateChecksum {
print("wrong request code \(self.requestOpCode?.description)")
return nil
}
if self.resultCode != SecureDFUResultCode.success {
print("Failed with eror: \(self.resultCode?.description)")
return nil
}
var reportedOffsetLE:[UInt8] = [UInt8](repeating: 0, count: 4)
(data as NSData).getBytes(&reportedOffsetLE, range: NSRange(location: 3, length: 4))
let offsetResult: UInt32 = reportedOffsetLE.reversed().reduce(UInt32(0)) {
$0 << 0o10 + UInt32($1)
}
self.offset = Int(offsetResult)
var reportedCRCLE:[UInt8] = [UInt8](repeating: 0, count: 4)
(data as NSData).getBytes(&reportedCRCLE, range: NSRange(location: 4, length: 4))
let crcResult: UInt32 = reportedCRCLE.reversed().reduce(UInt32(0)) {
$0 << 0o10 + UInt32($1)
}
self.crc = UInt32(crcResult)
}
}
internal class SecureDFUControlPoint : NSObject, CBPeripheralDelegate {
static let UUID = CBUUID(string: "8EC90001-F315-4F60-9FB8-838830DAEA50")
static func matches(_ characteristic:CBCharacteristic) -> Bool {
return characteristic.uuid.isEqual(UUID)
}
fileprivate var characteristic:CBCharacteristic
fileprivate var logger:LoggerHelper
fileprivate var success : SDFUCallback?
fileprivate var proceed : SecureDFUProgressCallback?
fileprivate var report : SDFUErrorCallback?
fileprivate var request : SecureDFURequest?
fileprivate var uploadStartTime : CFAbsoluteTime?
var valid:Bool {
return characteristic.properties.isSuperset(of: [CBCharacteristicProperties.write, CBCharacteristicProperties.notify])
}
// MARK: - Initialization
init(_ characteristic:CBCharacteristic, _ logger:LoggerHelper) {
self.characteristic = characteristic
self.logger = logger
}
func getValue() -> Data? {
return characteristic.value
}
func uploadFinished() {
self.proceed = nil
}
// MARK: - Characteristic API methods
/**
Enables notifications for the DFU ControlPoint characteristics. Reports success or an error
using callbacks.
- parameter success: method called when notifications were successfully enabled
- parameter report: method called in case of an error
*/
func enableNotifications(onSuccess success:SDFUCallback?, onError report:SDFUErrorCallback?) {
// Save callbacks
self.success = success
self.report = report
// Get the peripheral object
let peripheral = characteristic.service.peripheral
// Set the peripheral delegate to self
peripheral.delegate = self
logger.v("Enabling notifiactions for \(DFUControlPoint.UUID.uuidString)...")
logger.d("peripheral.setNotifyValue(true, forCharacteristic: \(DFUControlPoint.UUID.uuidString))")
peripheral.setNotifyValue(true, for: characteristic)
}
func send(_ request:SecureDFURequest, onSuccess success:SDFUCallback?, onError report:SDFUErrorCallback?) {
// Save callbacks and parameter
self.success = success
self.report = report
self.request = request
// Get the peripheral object
let peripheral = characteristic.service.peripheral
// Set the peripheral delegate to self
peripheral.delegate = self
switch request {
case .createData(let size):
logger.a("Writing \(request.description), \(size/8) bytes")
break
case .createCommand(let size):
logger.a("Writing \(request.description), \(size/8) bytes")
break
case .setPacketReceiptNotification(let size):
logger.a("Writing \(request.description), \(size) packets")
break
default:
logger.a("Writing \(request.description)...")
break
}
logger.v("Writing to characteristic \(SecureDFUControlPoint.UUID.uuidString)...")
logger.d("peripheral.writeValue(0x\(request.data.hexString), forCharacteristic: \(SecureDFUControlPoint.UUID.uuidString), type: WithResponse)")
peripheral.writeValue(request.data, for: characteristic, type: CBCharacteristicWriteType.withResponse)
}
func waitUntilUploadComplete(onSuccess success:SDFUCallback?, onPacketReceiptNofitication proceed:SecureDFUProgressCallback?, onError report:SDFUErrorCallback?) {
// Save callbacks. The proceed callback will be called periodically whenever a packet receipt notification is received. It resumes uploading.
self.success = success
self.proceed = proceed
self.report = report
self.uploadStartTime = CFAbsoluteTimeGetCurrent()
// Get the peripheral object
let peripheral = characteristic.service.peripheral
// Set the peripheral delegate to self
peripheral.delegate = self
logger.a("Uploading firmware...")
logger.v("Sending firmware DFU Packet characteristic...")
}
// MARK: - Peripheral Delegate callbacks
func peripheral(_ peripheral: CBPeripheral, didUpdateNotificationStateFor characteristic: CBCharacteristic, error: Error?) {
if error != nil {
logger.e("Enabling notifications failed")
logger.e(error!)
report?(SecureDFUError.enablingControlPointFailed, "Enabling notifications failed")
} else {
logger.v("Notifications enabled for \(SecureDFUControlPoint.UUID.uuidString)")
logger.a("DFU Control Point notifications enabled")
success?(nil)
}
}
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
if error != nil {
} else {
}
}
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
guard error == nil else {
// This characteristic is never read, the error may only pop up when notification is received
logger.e("Receiving notification failed")
logger.e(error!)
report?(SecureDFUError.receivingNotificationFailed, SecureDFUError.receivingNotificationFailed.description)
return
}
// During the upload we may get either a Packet Receipt Notification, or a Response with status code
if proceed != nil {
if let prn = SecureDFUPacketReceiptNotification(characteristic.value!) {
proceed!(prn.offset)
return
}
}
//Otherwise...
proceed = nil
logger.i("Notification received from \(characteristic.uuid.uuidString), value (0x):\(characteristic.value!.hexString)")
// Parse response received
let response = SecureDFUResponse(characteristic.value!)
if let response = response {
logger.a("\(response.description) received")
if response.status == SecureDFUResultCode.success {
switch response.requestOpCode! {
case .readObjectInfo:
success?(response.responseData)
break
case .createObject:
success?(response.responseData)
break
case .setPRNValue:
success?(response.responseData)
break
case .calculateChecksum:
success?(response.responseData)
break
case .readError:
success?(response.responseData)
break
case .execute:
success?(nil)
break
default:
success?(nil)
break
}
} else {
logger.e("Error \(response.status?.description): \(response.status?.description)")
report?(SecureDFUError(rawValue: Int(response.status!.rawValue))!, response.status!.description)
}
} else {
logger.e("Unknown response received: 0x\(characteristic.value!.hexString)")
report?(SecureDFUError.unsupportedResponse, SecureDFUError.unsupportedResponse.description)
}
}
}
| mit | 53d98ca99f82f35bda5ebf61250c20aa | 41.372727 | 178 | 0.627172 | 4.96247 | false | false | false | false |
DivineDominion/mac-multiproc-code | RelocationManagerServiceDomainTests/EndpointTests.swift | 1 | 3299 | //
// EndpointTests.swift
// RelocationManager
//
// Created by Christian Tietze on 20/03/15.
// Copyright (c) 2015 Christian Tietze. All rights reserved.
//
import Cocoa
import XCTest
import RelocationManagerServiceDomain
class EndpointTests: XCTestCase {
class TestManageBoxes: ManageBoxes {
struct Order {
let label: String
let capacity: Int
}
var lastOrder: Order?
override func orderBox(label: String, capacity: Int) {
lastOrder = Order(label: label, capacity: capacity)
}
var lastRemoval: IntegerId?
override func removeBox(boxIdentifier: IntegerId) {
lastRemoval = boxIdentifier
}
}
class TestManageItems: ManageItems {
var lastDistributedTitle: String?
override func distributeItem(title: String) {
lastDistributedTitle = title
}
struct Removal {
let itemIdentifier: IntegerId
let boxIdentifier: IntegerId
}
var lastRemoval: Removal?
override func removeItem(itemIdentifier: IntegerId, fromBoxIdentifier boxIdentifier: IntegerId) {
lastRemoval = Removal(itemIdentifier: itemIdentifier, boxIdentifier: boxIdentifier)
}
}
let boxManagementDouble = TestManageBoxes()
let itemManagementDouble = TestManageItems()
lazy var endpoint: Endpoint = Endpoint(manageBoxes: self.boxManagementDouble, manageItems: self.itemManagementDouble)
// MARK: Box Management
func testOrderBox_DelegatesToBoxManager() {
let label = "a label"
let capacity = 456
endpoint.orderBox(label, capacity: capacity)
if let order = boxManagementDouble.lastOrder {
XCTAssertEqual(order.label, label)
XCTAssertEqual(order.capacity, capacity)
} else {
XCTFail("no box order delegated")
}
}
func testRemoveBox_DelegatesToBoxManager() {
let expectedIdentifier: IntegerId = 1235
endpoint.removeBox(boxIdentifier: expectedIdentifier)
if let identifier = boxManagementDouble.lastRemoval {
XCTAssertEqual(identifier, expectedIdentifier)
} else {
XCTFail("no removal delegated")
}
}
// MARK: Item Management
func testDistributeItem_DelegatesToItemManager() {
let title = "some title"
endpoint.distributeItem(title)
if let distributedTitle = itemManagementDouble.lastDistributedTitle {
XCTAssertEqual(distributedTitle, title)
} else {
XCTFail("no item distributed")
}
}
func testRemoveItem_DelegatestoItemManager() {
let itemIdentifier: IntegerId = 558899
let boxIdentifier: IntegerId = 91235
endpoint.removeItem(itemIdentifier: itemIdentifier, fromBoxWithIdentifier: boxIdentifier)
if let removal = itemManagementDouble.lastRemoval {
XCTAssertEqual(removal.itemIdentifier, itemIdentifier)
XCTAssertEqual(removal.boxIdentifier, boxIdentifier)
} else {
XCTFail("no removal delegated")
}
}
}
| mit | 76ece5f46c43538cd8a23768404046d7 | 28.19469 | 121 | 0.625644 | 5.195276 | false | true | false | false |
mobileforming/WiremockClient | Sources/WiremockClient/Networking/WiremockClientNetworkService.swift | 1 | 2031 | //
// WiremockClientNetworkService.swift
// WiremockClientPackageDescription
//
// Created by Ted Rothrock on 2/12/21.
//
import Foundation
protocol SynchronousURLSession {
func executeSynchronousRequest(_ request: URLRequest) -> Result<Data?, Error>
}
extension URLSession: SynchronousURLSession {
func executeSynchronousRequest(_ request: URLRequest) -> Result<Data?, Error> {
var data: Data?
var error: Error?
let semaphore = DispatchSemaphore(value: 0)
let task = dataTask(with: request) { responseData, _, responseError in
data = responseData
error = responseError
semaphore.signal()
}
task.resume()
semaphore.wait()
if let error = error {
return .failure(error)
} else {
return .success(data)
}
}
}
struct WiremockClientNetworkService: NetworkService {
@DebugOverridable
var urlSession: SynchronousURLSession = URLSession.shared
func makeSynchronousRequest(with endpoint: Endpoint) throws {
guard let urlRequest = endpoint.urlRequest else {
throw WiremockClientError.invalidUrl
}
let result = urlSession.executeSynchronousRequest(urlRequest)
switch result {
case .success:
return
case .failure(let error):
throw error
}
}
func makeSynchronousRequest<T: Decodable>(with endpoint: Endpoint) throws -> T {
guard let urlRequest = endpoint.urlRequest else {
throw WiremockClientError.invalidUrl
}
let result = urlSession.executeSynchronousRequest(urlRequest)
switch result {
case .success(let data):
guard let data = data else {
throw WiremockClientError.decodingError
}
return try JSONDecoder().decode(T.self, from: data)
case .failure(let error):
throw error
}
}
}
| mit | 06d2aa7a27ec3e6ce64ef7e61421615d | 27.208333 | 84 | 0.608075 | 5.128788 | false | false | false | false |
redlock/JAYSON | JAYSON/Classes/Shifter.swift | 2 | 9101 | //
// Shifter.swift
// Pods
//
// Created by Redlock on 4/22/17.
//
//
import Foundation
public enum ShifterError: Error {
case PropertyNotFound(String)
case PopertyConversionError(String)
case NoDisplayStyleFound
case UnsupportedType(String)
}
public class Shifter<T> {
var errorMessages:[ShifterError] = []
var instance:T
var mirror:Mirror
var propKeyMap:[PropertyToJSONKeyMap] = []
/**
* instance: The instance you want to transform to or from json
* propKeyMap: an array of tuples to map json keys to property names. use custom operator as follows: propName <- jsonkey
ex: {
let testShifter = Shifter(instance: SimpleClass()) {
return ["numProp" <- "Numpy"]
}
*/
public init(instance:T, propKeyMap: (() -> [PropertyToJSONKeyMap])? = nil ){
if propKeyMap != nil {
self.propKeyMap = propKeyMap!()
}
self.instance = instance
self.mirror = Mirror(reflecting: instance)
}
private func getTypeOfProp(propKey:String) -> String? {
for (label, value) in self.mirror.children {
if propKey == label {
return String(describing: type(of: value))
// let propMirror = Mirror(reflecting: value)
// return propMirror.subjectType
}
}
return nil
}
private func getPropNameForJsonKey(_ key:String) -> String? {
for m in self.propKeyMap {
if m.jsonKey == key { return m.propName }
}
return nil
}
public func convert( from:JAYSON) -> T {
for (key, value) in from.dictionaryValue {
let propKey = getPropNameForJsonKey(key) ?? key
guard var propertyType = getTypeOfProp(propKey: propKey) else {
self.errorMessages.append(ShifterError.PropertyNotFound(key))
continue
}
if propertyType.contains("Optional<") {
guard let optionalType = propertyType.slice(from: "<", to: ">") else {
self.errorMessages.append(ShifterError.PropertyNotFound(key))
continue
}
propertyType = optionalType
}
switch propertyType {
case "String":
try! set(value.stringValue, key: propKey, for: &self.instance)
case "Int": try! set(value.intValue, key: propKey, for: &self.instance)
case "Float": try! set(value.floatValue, key: propKey, for: &self.instance)
case "Double": try! set(value.doubleValue, key: propKey, for: &self.instance)
case "Decimal": try! set(value.numberValue.decimalValue, key: propKey, for: &self.instance)
case "Bool": try! set(value.boolValue, key: propKey, for: &self.instance)
default:
self.errorMessages.append(ShifterError.UnsupportedType(propertyType))
}
}
return instance
}
public func shift(instance:Any) -> Data {
return try! JSONSerialization.data(withJSONObject: prepareObjectForJSON(instance: instance), options: .prettyPrinted)
}
var coreDictionary: [String:Any] = [:]
func prepareObjectForJSON(instance:Any) -> [String: Any] {
var dictionary: [String: Any] = [:]
let mirror = Mirror(reflecting: instance)
for case let (OptionalLabel, value) in mirror.children {
let propMirror = Mirror(reflecting: value)
var finalVal = value
guard let label = OptionalLabel else {
errorMessages.append(ShifterError.PopertyConversionError("label is nil for value :\(value)"))
continue
}
if self.isPrimitive(instance: finalVal) {
dictionary[label] = finalVal
continue
}
guard let displayStyle = propMirror.displayStyle else {
errorMessages.append(ShifterError.NoDisplayStyleFound)
continue
}
switch displayStyle {
case .class: finalVal = prepareObjectForJSON(instance: value)
case .struct: finalVal = prepareObjectForJSON(instance: value)
case .enum: finalVal = prepareObjectForJSON(instance: value)
case .collection:
finalVal = processCollection(instance: value as! Array<Any>)
// case .set: finalVal = processCollection(instance: value as! Set<AnyObject>)
case .dictionary: finalVal = prepareObjectForJSON(instance: value)
case .optional:
if let unwrapped = value as! Optional<Any> {
dictionary[label] = prepareObjectForJSON(instance: unwrapped)
}else{
dictionary[label] = value as! Optional<Any>
}
continue
//finalVal = value as! Optional<Any>
default:
errorMessages.append(ShifterError.UnsupportedType(String(describing: displayStyle)))
continue
}
dictionary[label] = finalVal
}
return dictionary
}
func isPrimitive(instance: Any) -> Bool {
switch String(describing: type(of: instance)) {
case "String",
"Int",
"Float",
"Double",
"Decimal",
"Bool": return true
default:
return false
}
}
func processCollection<T: Collection>(instance: T) -> [Any] {
var arr:[Any] = []
for item in instance {
if self.isPrimitive(instance: item) {
arr.append(item)
}else{
arr.append(prepareObjectForJSON(instance: item))
}
}
return arr
}
}
extension String {
func slice(from: String, to: String) -> String? {
return (range(of: from)?.upperBound).flatMap { substringFrom in
(range(of: to, range: substringFrom..<endIndex)?.lowerBound).map { substringTo in
substring(with: substringFrom..<substringTo)
}
}
}
}
class SimpleClass {
let junk:Int? = nil
let prop1 = "yeah"
let prop2 = "don't want to change man"
let numProp = 550
let items = ["one","two","ok"]
let nested = NestedClass(father: "abdul")
let nestedArray = [NestedClass(father:"the Dude"), NestedClass(father:"Mah "),]
}
class NestedClass {
let father:String
init(father:String) {
self.father = father
}
let name = "fahad"
let age = 36
}
public func fromJSONTestShifter(){
let simpleJSON:[String : Any] = [
"junk": 5,
"prop1": "no",
"Numpy": 440
]
let testShifter = Shifter(instance: SimpleClass()) {
// propName <- jsonkey
return ["junk" <- "Numpy"]
}
let updated = testShifter.convert(from: JAYSON(simpleJSON))
print(updated.junk)
print(updated.prop1)
print("updated.numProp: \(updated.numProp)")
print("updated.junk: \(updated.junk)")
print(updated.prop2)
}
public func toJSONTestShifter(){
let simple = SimpleClass()
let testShifter = Shifter(instance: simple)
// let updated = testShifter.convert(from: JSON(simpleJSON))
print( String(data: testShifter.shift(instance: SimpleClass()) , encoding: String.Encoding.utf8)!)
print("========== Errors ==========")
print(testShifter.errorMessages)
}
public typealias PropertyToJSONKeyMap = (propName: String,jsonKey: String)
infix operator <- : AdditionPrecedence
//infix operator <- { associativity left }
public func <- (propName: String, jsonKey: String) -> PropertyToJSONKeyMap {
return (propName, jsonKey)
}
enum OrderSide: Int {
case bid = 1
case ask = 2
}
struct Order {
var id:String //used to find the instance in the json dictionary
var price: Double?
var volume:Int?
var numberOfOrders:Int?
var orderSide: OrderSide?
init(id:String) {
self.id = id
}
}
| mit | 50792fd2e8a561d05ebd18d06cadbd41 | 24.70904 | 125 | 0.517635 | 4.846113 | false | false | false | false |
TongLin91/DSA-Challenges | DSAPlayground-LeetCode.playground/Pages/500-549.xcplaygroundpage/Contents.swift | 1 | 647 | import Foundation
//506 Relative Ranks
func findRelativeRanks(_ nums: [Int]) -> [String] {
var dict: [Int:Int] = [:]
var finalArr: [String] = nums.map{String($0)}
for index in 0..<nums.count{
dict[nums[index]] = index
}
var count = 1
for num in nums.sorted(by: >){
switch count {
case 1:
finalArr[dict[num]!] = "Gold Medal"
case 2:
finalArr[dict[num]!] = "Silver Medal"
case 3:
finalArr[dict[num]!] = "Bronze Medal"
default:
finalArr[dict[num]!] = String(count)
}
count += 1
}
return finalArr
}
| apache-2.0 | 02146435908d7c578fe0566406032ddb | 22.107143 | 51 | 0.513138 | 3.594444 | false | false | false | false |
wavecos/curso_ios_3 | Playgrounds/Opcionales.playground/section-1.swift | 1 | 653 | // Playground - Opcionales
import UIKit
var temperatura : Int?
temperatura = 21
if temperatura != nil {
println("La temperatura ambiente es \(temperatura!) grados celcius")
} else {
println("Hay un error en la obtencion de la temperatura")
}
var aeropuertos = ["ALT" : "Aeropuerto El Alto", "WLR" : "Aeropuerto Jorge Wilsterman", "JFK" : "Aeropuerto Jhon F. Kennedy"]
var resultado = aeropuertos["JFH"]
if resultado != nil {
println("El aeropuerto mas cercano es \(resultado!)")
}
// O Mejor asigando y comprobando directamente en el IF
if let resultado = aeropuertos["JFK"] {
println("El aeropuerto mas cercano es \(resultado)")
}
| apache-2.0 | d13e4bd00364f8dd65e3e52994728e03 | 20.064516 | 125 | 0.701378 | 2.941441 | false | false | false | false |
DrewKiino/Pacific | Pacific/Source/AppHttp.swift | 1 | 2775 | //
// AppHttp.swift
// boilerplate-ios-app
//
// Created by Andrew Aquino on 5/31/16.
// Copyright © 2016 Andrew Aquino. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
import AssetsLibrary
public typealias HttpResponseBlock = (json: JSON?, error: NSError?) -> Void
extension App {
public static func UPLOAD(endpoint: String, data: NSData?, filename: String? = nil, key: String?, progress: (Float -> Void)? = nil, completionHandler: HttpResponseBlock) {
if let data = data, let key = key {
Alamofire.upload(
.POST,
App.serverURL + endpoint,
headers: [
"key": key
] as [ String: String ],
multipartFormData: { multipartFormData in
multipartFormData.appendBodyPart(data: data, name: "file")
},
encodingCompletion: { encodingResult in
switch encodingResult {
case .Success(let upload, _, _):
upload.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
dispatch_async(dispatch_get_main_queue(), {
/**
* Update UI Thread about the progress
*/
progress?(Float(totalBytesWritten) / Float(totalBytesExpectedToWrite))
})
}
upload.response { req, res, data, error in
if let error = error {
log.error(error)
completionHandler(json: nil, error: error)
} else if let data = data {
completionHandler(json: JSON(data: data), error: nil)
}
}
case .Failure(let error):
log.error(error)
completionHandler(json: nil, error: nil)
//Show Alert in UI
}
}
)
}
}
public static func POST(endPoint: String, parameters: [ String: AnyObject ], responseBlock: HttpResponseBlock) {
Alamofire.request(.POST, App.serverURL + endPoint, parameters: parameters)
.response { (req, res, data, error) in
if let error = error {
log.error(error)
responseBlock(json: nil, error: error)
} else if let data = data, let json: JSON! = JSON(data: data) {
responseBlock(json: json, error: nil)
}
}
}
public static func GET(endPoint: String, parameters: [ String: AnyObject ]? = nil, responseBlock: HttpResponseBlock) {
Alamofire.request(.GET, App.serverURL + endPoint, parameters: parameters)
.response { (req, res, data, error) in
if let error = error {
log.error(error)
responseBlock(json: nil, error: error)
} else if let data = data, let json: JSON! = JSON(data: data) {
responseBlock(json: json, error: nil)
}
}
}
} | mit | 1be672338f3818b8b1c9596e5a651402 | 33.259259 | 173 | 0.586878 | 4.452648 | false | false | false | false |
contentful-labs/markdown-example-ios | Code/AppDelegate.swift | 1 | 1302 | //
// AppDelegate.swift
// Markdown
//
// Created by Boris Bügling on 01/12/15.
// Copyright © 2015 Contentful GmbH. All rights reserved.
//
import Contentful
import UIKit
let client = Contentful.Client(spaceIdentifier: "z57xujtsbou0", accessToken: "d81a8212a5a4f65bd27c5032d90b3670d2a80192e4918b2a911e0c4d0c763bbf")
func showError(_ error: Error, _ vc: UIViewController) {
let alertController = UIAlertController(title: "Error", message: "\(error)", preferredStyle: .alert)
vc.present(alertController, animated: true, completion: nil)
}
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let tabBarController = UITabBarController()
tabBarController.title = "Contentful Markdown Example"
tabBarController.viewControllers = [MDWebViewController(), MDTextViewController(), MDEmbedlyViewController()]
window = UIWindow(frame: UIScreen.main.bounds)
window?.backgroundColor = UIColor.white
window?.rootViewController = UINavigationController(rootViewController: tabBarController)
window?.makeKeyAndVisible()
return true
}
}
| mit | 802c54f5280736723da3098e92c2d4ab | 37.235294 | 144 | 0.75 | 4.513889 | false | false | false | false |
andrzejsemeniuk/ASToolkit | ASTookitShowcase/ViewController.swift | 1 | 3220 | //
// ViewController.swift
// ASTookitShowcase
//
// Created by andrzej semeniuk on 8/29/17.
// Copyright © 2017 Andrzej Semeniuk. All rights reserved.
//
import UIKit
import ASToolkit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
if false {
let picker = GenericControllerOfPickerOfColor()
picker.rowHeight = 80
let colors:[[UIColor]] = [
[.red,.orange,.yellow],
[.blue,.green,.aqua],
[.white],
[.red,.orange,.yellow],
[.blue,.green,.aqua],
[.white,.lightGray,.gray,.darkGray,.black],
[.red,.orange,.yellow],
[.blue,.green,.aqua],
[.white,.lightGray,.gray,.darkGray,.black],
[.red,.orange,.yellow],
[.blue,.green,.aqua],
[.white,.lightGray,.gray,.darkGray,.black],
[.red,.orange,.yellow],
[.blue,.green,.aqua],
[.white,.lightGray,.gray,.darkGray,.black],
[.red,.orange,.yellow],
[.blue,.green,.aqua],
[.white,.lightGray,.gray,.darkGray,.black],
[.red,.orange,.yellow],
[.blue,.green,.aqua],
[.gray],
]
picker.flavor = .matrixOfSolidCircles(selected: .white, colors: colors, diameter: 60, space: 16)
}
else if true {
// display, controls, storage
// display = circle, 2 circles, fill, custom, text on bg
let picker = GenericPickerOfColor.create(withComponents: [
.colorDisplay (height:64,kind:.dot),
// .sliderRed (height:16),
// .sliderGreen (height:16),
// .sliderBlue (height:16),
.sliderAlpha (height:32),
.sliderHue (height:16),
.sliderSaturation (height:16),
.sliderBrightness (height:16),
// .sliderCyan (height:32),
// .sliderMagenta (height:32),
// .sliderYellow (height:32),
// .sliderKey (height:32),
.storageDots (radius:16, columns:6, rows:3, colors:[.white,.gray,.black,.orange,.red,.blue,.green,.yellow])
])
picker.frame = UIScreen.main.bounds
self.view = picker
picker.backgroundColor = UIColor(white:0.95)
picker.handler = { color in
print("new color\(color)")
}
picker.set(color:UIColor(rgb:[0.64,0.13,0.78]), animated:true)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 636337b70e2c087fa4822f24a93e4bc1 | 36.870588 | 134 | 0.460702 | 4.892097 | false | false | false | false |
MLSDev/TRON | Source/TRON/TRONCodable.swift | 1 | 6187 | //
// TRONCodable.swift
// TRON
//
// Created by Denys Telezhkin on 06.02.16.
// Copyright © 2015 - present MLSDev. 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.
import Foundation
import Alamofire
/// `CodableParser` is a wrapper around `modelDecoder` and `errorDecoder` JSONDecoders to be used when decoding JSON response.
open class CodableParser<Model: Decodable>: DataResponseSerializerProtocol {
/// Decoder used for decoding model object
public let modelDecoder: JSONDecoder
/// Creates `CodableParser` with model and error decoders
public init(modelDecoder: JSONDecoder) {
self.modelDecoder = modelDecoder
}
/// Method used by response handlers that takes a request, response, data and error and returns a result.
open func serialize(request: URLRequest?, response: HTTPURLResponse?, data: Data?, error: Error?) throws -> Model {
if let error = error {
throw error
}
if let type = Model.self as? EmptyResponse.Type, let emptyValue = type.emptyValue() as? Model {
return emptyValue
}
return try modelDecoder.decode(Model.self, from: data ?? Data())
}
}
/// Serializer for objects, that conform to `Decodable` protocol.
open class CodableSerializer {
/// `TRON` instance to be used to send requests
let tron: TRON
/// Decoder to be used while parsing model.
public let modelDecoder: JSONDecoder
/// Creates `CodableSerializer` with `tron` instance to send requests, and `decoder` to be used while parsing response.
public init(_ tron: TRON, modelDecoder: JSONDecoder = JSONDecoder()) {
self.tron = tron
self.modelDecoder = modelDecoder
}
/**
Creates APIRequest with specified relative path and type RequestType.Default.
- parameter path: Path, that will be appended to current `baseURL`.
- returns: APIRequest instance.
*/
open func request<Model: Decodable, ErrorModel: ErrorSerializable>(_ path: String) -> APIRequest<Model, ErrorModel> {
return tron.request(path, responseSerializer: CodableParser(modelDecoder: modelDecoder))
}
/**
Creates APIRequest with specified relative path and type RequestType.UploadFromFile.
- parameter path: Path, that will be appended to current `baseURL`.
- parameter fileURL: File url to upload from.
- returns: APIRequest instance.
*/
open func upload<Model: Decodable, ErrorModel: ErrorSerializable>(_ path: String, fromFileAt fileURL: URL) -> UploadAPIRequest<Model, ErrorModel> {
return tron.upload(path, fromFileAt: fileURL,
responseSerializer: CodableParser(modelDecoder: modelDecoder))
}
/**
Creates APIRequest with specified relative path and type RequestType.UploadData.
- parameter path: Path, that will be appended to current `baseURL`.
- parameter data: Data to upload.
- returns: APIRequest instance.
*/
open func upload<Model: Decodable, ErrorModel: ErrorSerializable>(_ path: String, data: Data) -> UploadAPIRequest<Model, ErrorModel> {
return tron.upload(path, data: data, responseSerializer: CodableParser(modelDecoder: modelDecoder))
}
/**
Creates APIRequest with specified relative path and type RequestType.UploadStream.
- parameter path: Path, that will be appended to current `baseURL`.
- parameter stream: Stream to upload from.
- returns: APIRequest instance.
*/
open func upload<Model: Decodable, ErrorModel: ErrorSerializable>(_ path: String, from stream: InputStream) -> UploadAPIRequest<Model, ErrorModel> {
return tron.upload(path, from: stream, responseSerializer: CodableParser(modelDecoder: modelDecoder))
}
/**
Creates MultipartAPIRequest with specified relative path.
- parameter path: Path, that will be appended to current `baseURL`.
- parameter formData: Multipart form data creation block.
- returns: MultipartAPIRequest instance.
*/
open func uploadMultipart<Model: Decodable, ErrorModel: ErrorSerializable>(_ path: String,
encodingMemoryThreshold: UInt64 = MultipartFormData.encodingMemoryThreshold,
fileManager: FileManager = .default,
formData: @escaping (MultipartFormData) -> Void) -> UploadAPIRequest<Model, ErrorModel> {
return tron.uploadMultipart(path, responseSerializer: CodableParser(modelDecoder: modelDecoder),
encodingMemoryThreshold: encodingMemoryThreshold,
fileManager: fileManager,
formData: formData)
}
}
extension TRON {
/// Creates `CodableSerializer` with current `TRON` instance and specific `modelDecoder`.
public func codable(modelDecoder: JSONDecoder) -> CodableSerializer {
return CodableSerializer(self, modelDecoder: modelDecoder)
}
}
| mit | 2e46d506a6d9fe2ea5c3c7bf0f783372 | 42.258741 | 168 | 0.680731 | 5.125104 | false | false | false | false |
mbrandonw/swift-fp | swift-fp/Either.swift | 1 | 2372 | //
// Either.swift
// swift-fp
//
// Created by Brandon Williams on 8/30/14.
// Copyright (c) 2014 Kickstarter. All rights reserved.
//
import Foundation
enum Either <A, B> {
case Left(@autoclosure () -> A)
case Right(@autoclosure () -> B)
}
/**
Printable, DebugPrintable
*/
extension Either : Printable, DebugPrintable {
var description: String {
get {
switch self {
case let .Left(left): return "{Left: \(left())}"
case let .Right(right): return "{Right: \(right())}"
}
}
}
var debugDescription: String {
get {
return self.description
}
}
}
/**
Functor
*/
func fmap <A, B, C, D> (f: A -> C, g: B -> D) -> Either<A, B> -> Either<C, D> {
return {either in
switch either {
case let .Left(left): return Either<C, D>.Left(f(left()))
case let .Right(right): return Either<C, D>.Right(g(right()))
}
}
}
// Either<_, B>
func fmap <A, B, C> (f: A -> C) -> Either<A, B> -> Either<C, B> {
return fmap(f, identity)
}
// Either<A, _>
func fmap <A, B, D> (g: B -> D) -> Either<A, B> -> Either<A, D> {
return fmap(identity, g)
}
/**
Monad
*/
// Either<_, B>
func bind <A, B, C> (x: Either<A, C>, f: A -> Either<B, C>) -> Either<B, C> {
switch x {
case let .Left(left): return f(left())
case let .Right(right): return .Right(right())
}
}
// Either<A, _>
func bind <A, B, D> (x: Either<A, B>, f: B -> Either<A, D>) -> Either<A, D> {
switch x {
case let .Left(left): return .Left(left())
case let .Right(right): return f(right())
}
}
infix operator >>= {associativity left}
func >>= <A, B, C> (x: Either<A, C>, f: A -> Either<B, C>) -> Either<B, C> {
return bind(x, f)
}
prefix operator >>= {}
prefix func >>= <A, B, C> (x: Either<A, C>) -> (A -> Either<B, C>) -> Either<B, C> {
return {f in
return bind(x, f)
}
}
postfix operator >>= {}
postfix func >>= <A, B, C> (f: A -> Either<B, C>) -> Either<A, C> -> Either<B, C> {
return {x in
return bind(x, f)
}
}
func >>= <A, B, D> (x: Either<A, B>, f: B -> Either<A, D>) -> Either<A, D> {
return bind(x, f)
}
prefix func >>= <A, B, D> (x: Either<A, B>) -> (B -> Either<A, D>) -> Either<A, D> {
return {f in
return bind(x, f)
}
}
postfix func >>= <A, B, D> (f: B -> Either<A, D>) -> Either<A, B> -> Either<A, D> {
return {x in
return bind(x, f)
}
}
/**
Applicative
*/
| mit | e9f99bcb2aa079c71b7f953c403524ef | 18.129032 | 84 | 0.528668 | 2.680226 | false | false | false | false |
xjmeplws/AGDropdown | AGDropdown/AGDropDownCell.swift | 1 | 1282 | //
// AGDropDownCell.swift
// test
//
// Created by huangyawei on 16/3/25.
// Copyright © 2016年 xjmeplws. All rights reserved.
//
import UIKit
class AGDropDownCell: UITableViewCell {
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func configCell(data: AGDropDownData?) {
guard let data = data else {
return
}
for v in self.contentView.subviews {
v.removeFromSuperview()
}
self.backgroundColor = data.backgroundColor
var label: UILabel
if let img = data.icon {
let imgView = UIImageView(frame: CGRectMake(5, 3, frame.height - 6, frame.height - 6))
imgView.image = img
self.contentView.addSubview(imgView)
label = UILabel(frame: CGRectMake(frame.height + 3, 0, frame.width - frame.height - 3, frame.height))
} else {
label = UILabel(frame: CGRectMake(5, 0, frame.width - 5, frame.height))
}
label.text = data.value
self.contentView.addSubview(label)
}
}
| mit | 19e53512dfa8645eed9d2761c51fcbd0 | 28.068182 | 113 | 0.605942 | 4.249169 | false | false | false | false |
wdkk/CAIM | Basic/answer/caim02_calc_A/basic/DrawingViewController.swift | 1 | 4158 | //
// DrawingViewController.swift
// CAIM Project
// https://kengolab.net/CreApp/wiki/
//
// Copyright (c) Watanabe-DENKI Inc.
// https://wdkk.co.jp/
//
// This software is released under the MIT License.
// https://opensource.org/licenses/mit-license.php
//
import UIKit
class DrawingViewController : CAIMViewController
{
// 表示ビューと画像データの変数
var view_grad_x:CAIMView = CAIMView(x: 0, y: 0, width: 320, height: 320)
var img_grad_x:CAIMImage = CAIMImage(width:320, height:320)
var view_grad_y:CAIMView = CAIMView(x: 320, y: 0, width: 320, height: 320)
var img_grad_y:CAIMImage = CAIMImage(width:320, height:320)
var view_grad_xy:CAIMView = CAIMView(x: 0, y: 320, width: 320, height: 320)
var img_grad_xy:CAIMImage = CAIMImage(width:320, height:320)
var view_grad_sin:CAIMView = CAIMView(x: 320, y: 320, width: 320, height: 320)
var img_grad_sin:CAIMImage = CAIMImage(width:320, height:320)
var view_grad_circle:CAIMView = CAIMView(x: 0, y: 640, width: 320, height: 320)
var img_grad_circle:CAIMImage = CAIMImage(width:320, height:320)
var view_grad_dome:CAIMView = CAIMView(x: 320, y: 640, width: 320, height: 320)
var img_grad_dome:CAIMImage = CAIMImage(width:320, height:320)
// はじめに1度だけ呼ばれる関数(アプリの準備)
override func setup() {
// 横方向グラデーション画像の作成
let cx1 = CAIMColor(R: 1.0, G: 0.0, B: 0.0, A: 1.0)
let cx2 = CAIMColor(R: 1.0, G: 1.0, B: 0.0, A: 1.0)
ImageToolBox.gradX(img_grad_x, color1:cx1, color2:cx2)
// view_grad_xの画像として、img_grad_xを設定する
view_grad_x.image = img_grad_x
// view_grad_xを画面に追加
self.view.addSubview( view_grad_x )
// 縦方向グラデーション画像の作成
let cy1 = CAIMColor(R: 0.0, G: 1.0, B: 0.0, A: 1.0)
let cy2 = CAIMColor(R: 0.2, G: 0.2, B: 1.0, A: 1.0)
ImageToolBox.gradY(img_grad_y, color1:cy1, color2:cy2)
// view_grad_yの画像として、img_grad_yを設定する
view_grad_y.image = img_grad_y
// view_grad_yを画面に追加
self.view.addSubview( view_grad_y )
// 斜め方向グラデーション画像の作成
let cxy1 = CAIMColor(R: 0.0, G: 0.5, B: 0.0, A: 1.0)
let cxy2 = CAIMColor(R: 1.0, G: 1.0, B: 0.0, A: 1.0)
ImageToolBox.gradXY(img_grad_xy, color1:cxy1, color2:cxy2)
// view_grad_xyの画像として、img_grad_xyを設定する
view_grad_xy.image = img_grad_xy
// view_grad_xを画面に追加
self.view.addSubview( view_grad_xy )
// 横方向Sin波グラデーション画像の作成
let csin1 = CAIMColor(R: 1.0, G: 1.0, B: 1.0, A: 1.0)
let csin2 = CAIMColor(R: 0.0, G: 0.0, B: 1.0, A: 1.0)
ImageToolBox.gradSin(img_grad_sin, color1:csin1, color2:csin2, k: 4.0)
// view_grad_sinの画像として、img_grad_sinを設定する
view_grad_sin.image = img_grad_sin
// view_grad_sinを画面に追加
self.view.addSubview( view_grad_sin )
// 同心円グラデーション画像の作成
let ccir1 = CAIMColor(R: 1.0, G: 0.5, B: 0.0, A: 1.0)
let ccir2 = CAIMColor(R: 1.0, G: 1.0, B: 1.0, A: 1.0)
ImageToolBox.gradSinCircle(img_grad_circle, color1:ccir1, color2:ccir2, k:4.0)
// view_grad_circleの画像として、img_grad_circleを設定する
view_grad_circle.image = img_grad_circle
// view_grad_circleを画面に追加
self.view.addSubview( view_grad_circle )
// Cosドーム画像の作成
let cdom1 = CAIMColor(R: 0.0, G: 0.0, B: 1.0, A: 1.0)
let cdom2 = CAIMColor(R: 1.0, G: 1.0, B: 1.0, A: 1.0)
ImageToolBox.gradCosDome(img_grad_dome, color1:cdom1, color2:cdom2)
// view_grad_domeの画像として、img_grad_domeを設定する
view_grad_dome.image = img_grad_dome
// view_grad_domeを画面に追加
self.view.addSubview( view_grad_dome )
}
}
| mit | a758d7fbea578315ce47e5be922d7f52 | 37.604167 | 86 | 0.605774 | 2.602528 | false | false | false | false |
hshssingh4/Tips-iOS-Project | Tips/SettingsViewController.swift | 1 | 6667 | //
// SettingsViewController.swift
// Tips
//
// Created by Harpreet on 12/6/15.
// Copyright © 2015 Harpreet. All rights reserved.
//
import UIKit
class SettingsViewController: UIViewController
{
@IBOutlet weak var tapControlSettings: UISegmentedControl!
//the segmented bar control for default tip
@IBOutlet weak var themeControl: UISegmentedControl!
//the theme bar control for changing themes
@IBOutlet weak var defaultTipLabel: UILabel!
@IBOutlet weak var themeLabel: UILabel!
@IBOutlet weak var defaultTipSwitch: UISwitch!
@IBOutlet weak var customTipSwitch: UISwitch!
@IBOutlet weak var customTipSlider: UISlider!
@IBOutlet weak var sliderLabel: UILabel!
@IBOutlet weak var customTipLabel: UILabel!
let defaults = NSUserDefaults.standardUserDefaults()
let originalTintColor: UIColor = UIColor(red: 0, green: 0.478431, blue: 1, alpha: 1)
/*
originalTintColor creates a color that mimics that of the original segmented
control since it is required to be accessed once the theme changes are made
*/
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
}
/*
Before this view diappears, setting like default tip and the theme are stored
so that the values in the tip view controller can be accordingly changed
*/
override func viewWillDisappear(animated: Bool)
{
super.viewWillDisappear(animated)
defaults.setInteger(tapControlSettings.selectedSegmentIndex, forKey: "indexDefaultTip")
defaults.setInteger(themeControl.selectedSegmentIndex, forKey: "indexThemeColor")
defaults.setBool(defaultTipSwitch.enabled, forKey: "defaultTipSwitch")
defaults.setInteger(Int(customTipSlider.value), forKey: "customTipValue")
if customTipSwitch.on
{
defaults.setBool(true, forKey: "customTipSlider")
}
else
{
defaults.setBool(false, forKey: "customTipSlider")
}
defaults.synchronize()
}
/*
Reads the default tip amount once chosen by user while using the app
and highlights the portion of the segmented bars accordingly
*/
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
let defaultTipIndex = defaults.integerForKey("indexDefaultTip")
switch defaultTipIndex
{
case 0...2:
tapControlSettings.selectedSegmentIndex = defaultTipIndex
default:
break
}
let defaultThemeIndex = defaults.integerForKey("indexThemeColor")
switch defaultThemeIndex
{
case 0...1:
themeControl.selectedSegmentIndex = defaultThemeIndex
themeChanged("")
default:
break
}
customTipSlider.value = Float(defaults.integerForKey("customTipValue"))
sliderLabel.text = String(Int(customTipSlider.value)) + " %"
if defaults.boolForKey("customTipSlider")
{
defaultTipSwitch.on = false
customTipSwitch.on = true
}
switchState("")
}
/*
Checks whether the theme is changed and performs the same operations
as descrived in calculateTip method of tipViewController class
*/
@IBAction func themeChanged(sender: AnyObject)
{
if themeControl.selectedSegmentIndex == 0
{
self.view.backgroundColor = UIColor.whiteColor()
defaultTipLabel.textColor = UIColor.blackColor()
themeLabel.textColor = UIColor.blackColor()
tapControlSettings.tintColor = originalTintColor
themeControl.tintColor = originalTintColor
customTipLabel.textColor = UIColor.blackColor()
sliderLabel.textColor = UIColor.blackColor()
customTipSlider.tintColor = originalTintColor
defaultTipSwitch.onTintColor = UIColor.greenColor()
customTipSwitch.onTintColor = UIColor.greenColor()
}
else if themeControl.selectedSegmentIndex == 1
{
self.view.backgroundColor = UIColor.blackColor()
defaultTipLabel.textColor = UIColor.whiteColor()
themeLabel.textColor = UIColor.whiteColor()
tapControlSettings.tintColor = UIColor.whiteColor()
themeControl.tintColor = UIColor.whiteColor()
customTipLabel.textColor = UIColor.whiteColor()
sliderLabel.textColor = UIColor.whiteColor()
customTipSlider.tintColor = UIColor.lightGrayColor()
defaultTipSwitch.onTintColor = UIColor.lightGrayColor()
customTipSwitch.onTintColor = UIColor.lightGrayColor()
}
}
@IBAction func sliderValueChanged(sender: AnyObject)
{
if customTipSwitch.on
{
customTipSlider.enabled = true
sliderLabel.text = String(Int(customTipSlider.value)) + " %"
defaults.setBool(true, forKey: "customTipSlider")
defaults.setInteger(Int(customTipSlider.value), forKey: "customTipValue")
}
else
{
customTipSlider.enabled = false
defaults.setBool(false, forKey: "customTipSlider")
}
}
@IBAction func switchState(sender: AnyObject)
{
if defaultTipSwitch.on
{
tapControlSettings.enabled = true
customTipSlider.enabled = false
customTipSwitch.on = false
}
else
{
tapControlSettings.enabled = false
customTipSlider.enabled = true
customTipSwitch.on = true
}
}
@IBAction func switchState2(sender: AnyObject)
{
if customTipSwitch.on
{
tapControlSettings.enabled = false
customTipSlider.enabled = true
defaultTipSwitch.on = false
}
else
{
tapControlSettings.enabled = true
customTipSlider.enabled = false
defaultTipSwitch.on = true
}
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| apache-2.0 | 84d2bcc784f37a08dc45536f9b0e1edf | 33.184615 | 106 | 0.643414 | 5.163439 | false | false | false | false |
jakubholik/mi-ios | mi-ios/GuideDetailViewModel.swift | 1 | 13271 | //
// GuideDetailViewModel.swift
//
// Created by Jakub Holík on 11.04.17.
// Copyright © 2017 Symphony No. 9 s.r.o. All rights reserved.
//
import Foundation
import RealmSwift
import AVFoundation
import AVKit
class GuideDetailViewModel: NSObject {
var delegate: GuideDetailViewController?
var placeTitle: String?
var placeDescription: String?
var posts: List<PlacePost>?
var currentAudioObject: AudioObject?
var audioObjects: [Int:AudioObject] = [:]
var zoomView = UIView()
var zoomedImageView = UIImageView()
var scrollView = UIScrollView()
let kHorizontalInsets: CGFloat = 10.0
let kVerticalInsets: CGFloat = 10.0
var offscreenCells = Dictionary<String, UICollectionViewCell>()
func viewWillDisappear(){
stopAudioTrack()
}
func registerCollectionViewCells(){
let cells = [
"ImageCell",
"AudioCell",
"VideoCell"
]
for cell in cells as [String] {
let myCellNib = UINib(nibName: "GuideDetail\(cell)", bundle: nil)
if let delegate = delegate {
delegate.collectionView.register(myCellNib, forCellWithReuseIdentifier: cell)
}
}
}
func initializeAudioPlayer(with fileName: String)->AVAudioPlayer {
if let audioPath = Bundle.main.path(forResource: fileName, ofType: "mp3") {
do{
let audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath))
return audioPlayer
} catch{
print("Couldn't initialize audio player for track: \(fileName)")
return AVAudioPlayer()
}
} else {
print("Couldn't find audio track: \(fileName)")
return AVAudioPlayer()
}
}
func initializeVideoPlayer(_ sender: UIButton){
if let superview = sender.superview {
if let cell = superview.superview as? GuideDetailVideoCell {
if let post = cell.post{
if let delegate = delegate{
if let videoPath = Bundle.main.path(forResource: post.mediaFileName, ofType: "mp4") {
let player = AVPlayer(url: URL(fileURLWithPath: videoPath))
let playerViewController = CellAVPlayerViewController()
playerViewController.player = player
playerViewController.collectionView = delegate.collectionView
self.delegate?.present(playerViewController, animated: true) {
playerViewController.player!.play()
}
}
}
}
}
}
}
@objc func toggleAudioTrack(_ sender: UIButton){
guard let superview = sender.superview,
let cell = superview.superview as? GuideDetailAudioCell else {
return
}
let object = audioObjects.map({
key, value in
if value.cell == cell {
if let player = value.audioPlayer {
if player.isPlaying {
player.pause()
value.timer = nil
} else {
player.play()
value.timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(updateProgressSlider), userInfo: cell, repeats: true)
}
}
}
})
}
func stopAudioTrack(){
_ = audioObjects.map({
key, value in
if let audioPlayer = value.audioPlayer {
if audioPlayer.isPlaying {
audioPlayer.stop()
}
}
})
}
func updateProgressSlider(timer: Timer){
guard let cell = timer.userInfo as? GuideDetailAudioCell,
let delegate = delegate,
let index = delegate.collectionView.indexPath(for: cell),
let audioObject = audioObjects[index.row],
let audioPlayer = audioObject.audioPlayer else {
return
}
UIView.animate(withDuration: 0.1, delay: 0.0, options: .curveLinear, animations: {
cell.progressView.setProgress(Float(audioPlayer.currentTime/audioPlayer.duration), animated: false)
}, completion: nil)
}
func configureCollectionViewCellData(with indexPath: IndexPath) -> UICollectionViewCell {
var cell = UICollectionViewCell()
guard let posts = posts,
let delegate = delegate,
posts.indices.contains(indexPath.row)
else {
return cell
}
let post = posts[indexPath.row]
if post.mediaType == PlacePostMediaType.image.rawValue {
if let cellView = delegate.collectionView.dequeueReusableCell(withReuseIdentifier: "ImageCell", for: indexPath) as? GuideDetailImageCell {
cellView.post = post
cellView.titleLabel.text = post.title
cellView.descriptionLabel.text = post.textContent
cellView.imageView.image = UIImage(named: post.mediaFileName)
cellView.setDate(with: post.date, label: cellView.dateLabel)
cellView.cellLayout()
cellView.imageView.tag = indexPath.row
cellView.layoutIfNeeded()
cellView.imageView.isUserInteractionEnabled = true
let tap = UITapGestureRecognizer(target: self, action: #selector(bringUpZoomView(_:)))
cellView.imageView.addGestureRecognizer(tap)
cell = cellView
}
} else if post.mediaType == PlacePostMediaType.audio.rawValue {
if let cellView = delegate.collectionView.dequeueReusableCell(withReuseIdentifier: "AudioCell", for: indexPath) as? GuideDetailAudioCell {
cellView.post = post
cellView.titleLabel.text = post.title
cellView.descriptionLabel.text = post.textContent
cellView.imageView.image = UIImage(named: "bg_audio")
cellView.setDate(with: post.date, label: cellView.dateLabel)
cellView.cellLayout()
if let object = audioObjects[indexPath.row] {
if let player = object.audioPlayer {
cellView.playButton.addTarget(self, action: #selector(toggleAudioTrack(_:)), for: .touchUpInside)
}
} else {
let object = AudioObject()
object.audioPlayer = initializeAudioPlayer(with: post.mediaFileName)
object.cell = cellView
audioObjects[indexPath.row] = object
cellView.playButton.addTarget(self, action: #selector(toggleAudioTrack(_:)), for: .touchUpInside)
}
cellView.layoutIfNeeded()
cell = cellView
}
} else if post.mediaType == PlacePostMediaType.video.rawValue {
if let cellView = delegate.collectionView.dequeueReusableCell(withReuseIdentifier: "VideoCell", for: indexPath) as? GuideDetailVideoCell {
cellView.post = post
cellView.titleLabel.text = post.title
cellView.descriptionLabel.text = post.textContent
cellView.imageView.image = UIImage(named: "bg_video")
cellView.setDate(with: post.date, label: cellView.dateLabel)
cellView.playButton.addTarget(self, action: #selector(initializeVideoPlayer(_:)), for: .touchUpInside)
cellView.cellLayout()
cellView.layoutIfNeeded()
cell = cellView
}
} else {
print("No cell match")
}
cell.layoutIfNeeded()
return cell
}
func configureCollectionViewCellSize(with indexPath: IndexPath) -> CGSize {
if let delegate = delegate {
let targetWidth = (delegate.collectionView.bounds.width - 3 * kHorizontalInsets)
if (posts?[indexPath.row]) != nil {
// Use fake cell to calculate height
let reuseIdentifier = "GuideDetailImageCell"
var cell: GuideDetailImageCell? = offscreenCells[reuseIdentifier] as? GuideDetailImageCell
if cell == nil {
cell = Bundle.main.loadNibNamed("GuideDetailImageCell", owner: self, options: nil)?[0] as? GuideDetailImageCell
self.offscreenCells[reuseIdentifier] = cell
}
if let post = posts?[indexPath.row] {
// Config cell and let system determine size
cell!.titleLabel.text = post.title
cell!.descriptionLabel.text = post.textContent
cell!.imageView.image = UIImage(named: "bg_nature")
cell!.cellLayout()
}
// Cell's size is determined in nib file, need to set it's width (in this case), and inside, use this cell's width to set label's preferredMaxLayoutWidth, thus, height can be determined, this size will be returned for real cell initialization
cell!.bounds = CGRect(x: 0, y: 0, width: targetWidth, height: cell!.bounds.height)
cell!.contentView.bounds = cell!.bounds
// Layout subviews, this will let labels on this cell to set preferredMaxLayoutWidth
cell!.setNeedsLayout()
cell!.layoutIfNeeded()
var size = cell!.contentView.systemLayoutSizeFitting(UILayoutFittingCompressedSize)
// Still need to force the width, since width can be smalled due to break mode of labels
size.width = targetWidth
return size
} else {
return CGSize.zero
}
} else {
return CGSize.zero
}
}
func initializeZoomView() {
guard let delegate = delegate else {
return
}
let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage(_:)))
zoomView.frame = CGRect(x: 0, y: 0, width: delegate.view.bounds.size.width, height: delegate.view.bounds.size.height)
zoomView.translatesAutoresizingMaskIntoConstraints = false
zoomedImageView.backgroundColor = .black
zoomedImageView.clipsToBounds = false
zoomedImageView.isUserInteractionEnabled = true
zoomedImageView.addGestureRecognizer(tap)
scrollView.frame = CGRect(x: 0, y: 0, width: zoomView.bounds.size.width, height: zoomView.bounds.size.height)
scrollView.alwaysBounceVertical = true
scrollView.alwaysBounceHorizontal = true
scrollView.showsVerticalScrollIndicator = false
scrollView.backgroundColor = .black
scrollView.isScrollEnabled = true
scrollView.contentSize = zoomedImageView.bounds.size
scrollView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
scrollView.minimumZoomScale = CGFloat(0.1)
scrollView.maximumZoomScale = CGFloat(4.0)
scrollView.zoomScale = 1.0
scrollView.delegate = delegate
scrollView.isMultipleTouchEnabled = true
scrollView.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(zoomedImageView)
zoomView.addSubview(scrollView)
//Leading
zoomView.addConstraint(NSLayoutConstraint(item: scrollView, attribute: .leading, relatedBy: .equal, toItem: zoomView, attribute: .leading, multiplier: 1, constant: 0))
//Bottom
zoomView.addConstraint(NSLayoutConstraint(item: zoomView, attribute: .bottom, relatedBy: .equal, toItem: scrollView, attribute: .bottom, multiplier: 1, constant: 0))
//Top
zoomView.addConstraint(NSLayoutConstraint(item: scrollView, attribute: .top, relatedBy: .equal, toItem: zoomView, attribute: .top, multiplier: 1, constant: 0))
//Trailing
zoomView.addConstraint(NSLayoutConstraint(item: zoomView, attribute: .trailing, relatedBy: .equal, toItem: scrollView, attribute: .trailing, multiplier: 1, constant: 0))
print("Initialized")
}
func setZoomViewConstraints(){
guard let delegate = delegate else {
return
}
//Leading
delegate.view.addConstraint(NSLayoutConstraint(item: delegate.view, attribute: .leading, relatedBy: .equal, toItem: zoomView, attribute: .leading, multiplier: 1, constant: 0))
//Bottom
delegate.view.addConstraint(NSLayoutConstraint(item: zoomView, attribute: .bottom, relatedBy: .equal, toItem: delegate.view, attribute: .bottom, multiplier: 1, constant: 0))
//Top
delegate.view.addConstraint(NSLayoutConstraint(item: delegate.view, attribute: .top, relatedBy: .equal, toItem: zoomView, attribute: .top, multiplier: 1, constant: 0))
//Trailing
delegate.view.addConstraint(NSLayoutConstraint(item: zoomView, attribute: .trailing, relatedBy: .equal, toItem: delegate.view, attribute: .trailing, multiplier: 1, constant: 0))
}
func bringUpZoomView(_ sender: UITapGestureRecognizer) {
print("Tapped")
guard let imageView = sender.view as? UIImageView,
let delegate = delegate,
let posts = posts,
posts.indices.contains(imageView.tag),
let image = UIImage(named: posts[imageView.tag].mediaFileName) else {
return
}
zoomedImageView.image = image
zoomedImageView.frame = CGRect(x: 0, y: 0, width: image.size.width*image.scale, height: image.size.height*image.scale)
let imageTopOffset = scrollView.frame.height/2 - image.size.height*(4/5)
var imageLeftOffset: CGFloat = 0.0
if scrollView.frame.width > (image.size.width * image.scale) {
imageLeftOffset = (scrollView.frame.width-(image.size.width*image.scale))/CGFloat(2)
} else {
imageLeftOffset = 0
}
scrollView.contentOffset = CGPoint(x: image.size.width, y: image.size.height)
scrollView.contentInset = UIEdgeInsetsMake(imageTopOffset - 44.0, imageLeftOffset, imageTopOffset, imageLeftOffset)
delegate.updateMinZoomScaleForSize(size: delegate.view.bounds.size)
UIView.transition(with: delegate.view, duration: 0.5, options: .transitionFlipFromRight,
animations: {
delegate.view.addSubview(self.zoomView)
self.setZoomViewConstraints()
}, completion: { (value: Bool) in
})
}
func dismissFullscreenImage(_ sender: UITapGestureRecognizer) {
print("Image tapped")
guard let delegate = delegate else {
return
}
UIView.transition(with: delegate.view, duration: 0.5, options: .transitionFlipFromLeft,
animations: {
self.zoomView.removeFromSuperview()
}, completion: { (value: Bool) in
})
}
func viewWillTransition(to size: CGSize) {
}
}
| mit | e3a6a21bd81a75868f5a082510f28e01 | 27.845652 | 246 | 0.697792 | 4.159561 | false | false | false | false |
lacklock/ReactiveCocoaExtension | Pods/ReactiveSwift/Sources/FoundationExtensions.swift | 2 | 4732 | //
// FoundationExtensions.swift
// ReactiveSwift
//
// Created by Justin Spahr-Summers on 2014-10-19.
// Copyright (c) 2014 GitHub. All rights reserved.
//
import Foundation
import Dispatch
import enum Result.NoError
import struct Result.AnyError
#if os(Linux)
import let CDispatch.NSEC_PER_USEC
import let CDispatch.NSEC_PER_SEC
#endif
extension NotificationCenter: ReactiveExtensionsProvider {}
extension Reactive where Base: NotificationCenter {
/// Returns a Signal to observe posting of the specified notification.
///
/// - parameters:
/// - name: name of the notification to observe
/// - object: an instance which sends the notifications
///
/// - returns: A Signal of notifications posted that match the given criteria.
///
/// - note: The signal does not terminate naturally. Observers must be
/// explicitly disposed to avoid leaks.
public func notifications(forName name: Notification.Name?, object: AnyObject? = nil) -> Signal<Notification, NoError> {
return Signal { [base = self.base] observer in
let notificationObserver = base.addObserver(forName: name, object: object, queue: nil) { notification in
observer.send(value: notification)
}
return ActionDisposable {
base.removeObserver(notificationObserver)
}
}
}
}
private let defaultSessionError = NSError(domain: "org.reactivecocoa.ReactiveSwift.Reactivity.URLSession.dataWithRequest",
code: 1,
userInfo: nil)
extension URLSession: ReactiveExtensionsProvider {}
extension Reactive where Base: URLSession {
/// Returns a SignalProducer which performs the work associated with an
/// `NSURLSession`
///
/// - parameters:
/// - request: A request that will be performed when the producer is
/// started
///
/// - returns: A producer that will execute the given request once for each
/// invocation of `start()`.
///
/// - note: This method will not send an error event in the case of a server
/// side error (i.e. when a response with status code other than
/// 200...299 is received).
public func data(with request: URLRequest) -> SignalProducer<(Data, URLResponse), AnyError> {
return SignalProducer { [base = self.base] observer, disposable in
let task = base.dataTask(with: request) { data, response, error in
if let data = data, let response = response {
observer.send(value: (data, response))
observer.sendCompleted()
} else {
observer.send(error: AnyError(error ?? defaultSessionError))
}
}
disposable += {
task.cancel()
}
task.resume()
}
}
}
extension Date {
internal func addingTimeInterval(_ interval: DispatchTimeInterval) -> Date {
return addingTimeInterval(interval.timeInterval)
}
}
extension DispatchTimeInterval {
internal var timeInterval: TimeInterval {
switch self {
case let .seconds(s):
return TimeInterval(s)
case let .milliseconds(ms):
return TimeInterval(TimeInterval(ms) / 1000.0)
case let .microseconds(us):
return TimeInterval( UInt64(us) * NSEC_PER_USEC ) / TimeInterval(NSEC_PER_SEC)
case let .nanoseconds(ns):
return TimeInterval(ns) / TimeInterval(NSEC_PER_SEC)
}
}
// This was added purely so that our test scheduler to "go backwards" in
// time. See `TestScheduler.rewind(by interval: DispatchTimeInterval)`.
internal static prefix func -(lhs: DispatchTimeInterval) -> DispatchTimeInterval {
switch lhs {
case let .seconds(s):
return .seconds(-s)
case let .milliseconds(ms):
return .milliseconds(-ms)
case let .microseconds(us):
return .microseconds(-us)
case let .nanoseconds(ns):
return .nanoseconds(-ns)
}
}
/// Scales a time interval by the given scalar specified in `rhs`.
///
/// - note: This method is only used internally to "scale down" a time
/// interval. Specifically it's used only to scale intervals to 10%
/// of their original value for the default `leeway` parameter in
/// `SchedulerProtocol.schedule(after:action:)` schedule and similar
/// other methods.
///
/// If seconds is over 200,000, 10% is ~2,000, and hence we end up
/// with a value of ~2,000,000,000. Not quite overflowing a signed
/// integer on 32-bit platforms, but close.
///
/// Even still, 200,000 seconds should be a rarely (if ever)
/// specified interval for our APIs. And even then, folks should be
/// smart and specify their own `leeway` parameter.
///
/// - returns: Scaled interval in microseconds
internal static func *(lhs: DispatchTimeInterval, rhs: Double) -> DispatchTimeInterval {
let seconds = lhs.timeInterval * rhs
return .microseconds(Int(seconds * 1000 * 1000))
}
}
| mit | 32164673915d115d5441de16368d6f12 | 32.8 | 122 | 0.690617 | 3.901072 | false | false | false | false |
f2m2/f2m2-swift-forms | ObjCExample/ObjCExample/ObjCExample/Generator/FormController.swift | 3 | 15143 | //
// FormSerializerClasses.swift
// FormSerializer
//
// Created by Michael L Mork on 12/1/14.
// Copyright (c) 2014 f2m2. All rights reserved.
//
import Foundation
import UIKit
/**
Simple convenience extensions on FormControllerProtocol-conforming UIViewController; tableview is provided and added.
*/
extension UIViewController: FormControllerProtocol {
/**
Convenience on convenience; provide only the form data data.
:param: data FormObjectProtocol-conforming objects.
:return: FormController a formController.
*/
public func newFormController (data: [FormObjectProtocol]) -> FormController {
return newFormController(data, headerView: nil)
}
/**
Provide data and a header view for a tableview which is added to self.
:param: data FormObjectProtocol-conforming objects.
:param: headerView an optional custom header for the tableView
:return: FormController a formController.
*/
public func newFormController (data: [FormObjectProtocol], headerView: UIView?) -> FormController {
let tableView = UITableView(frame: CGRectZero)
view.addSubview(tableView)
layout(tableView, view) { (TableView, View) -> () in
TableView.edges == inset(View.edges, 20, 0, 0, 0); return
}
if let headerView = headerView as UIView! {
tableView.tableHeaderView = headerView
}
let formController = FormController(data: data, tableView: tableView)
formController.delegate = self
return formController
}
}
/**
The EntityController holds the FormSerializationProtocol collection.
It sorts this collection in order to find the data which will be displayed.
It sorts to find the number of sections.
It sets its displayed data values as the interface is manipulated.
Meant-For-Consumption functions include:
/// - init: init with FormSerializationProtocol-conforming objects.
/// - validateForm: Validate all FormObjectProtocol objects which implement isValid().
/// - assembleSubmissionDictionary: Assemble a network SubmissionDictionary from the values set on the display data which are implementing the key variable in FormObjectProtocol.
/// - updateDataModelWithIdentifier: Update a FormObjectProtocolObject with a value and its user - given identifier.
*/
@objc public class FormController: NSObject, UITableViewDataSource, UITableViewDelegate {
let data: [FormObjectProtocol]
var delegate: FormControllerProtocol?
var tableView: UITableView
var customFormObjects: [String: FormObjectProtocol] = [String: FormObjectProtocol]()
var sectionHeaderTitles: [String] = [String]()
lazy var displayData: [FormObjectProtocol] = {
var mData = self.data
mData = sorted(mData) {
f0, f01 in
//Display order here.
return f0.rowIdx < f01.rowIdx
}
var nData = mData.filter { (T) -> Bool in
//filter whether to display here.
T.displayed == true
}
return nData
}()
/********
public
********/
/**
init with data conforming to the FormSerializationProtocol.
:param: data An array of objects conforming to the FormSerializationProtocol
:returns: self
*/
init(data: [FormObjectProtocol], tableView: UITableView) {
self.data = data
self.tableView = tableView
super.init()
tableView.registerClass(FormCell.self, forCellReuseIdentifier: "Cell")
tableView.delegate = self
tableView.dataSource = self
tableView.reloadData()
}
/**
Update the data model with identifier and the new value.
:param: identifier A string assigned to a given
:param: newValue Whatever type of anyObject the user desires to set on the given identifier's FormObjectProtocol object.
*/
func updateDataModelWithIdentifier(identifier: String, newValue: AnyObject) {
// if let formObject = customFormObjects?[identifier] as FormObjectProtocol? {
println("update data model: \(customFormObjects)")
updateDataModel(customFormObjects[identifier])
}
/**
Update the data model with a unique ForhObjectProtocol object.
:param: object A FormObjectProtocol object
*/
func updateDataModel(object: FormObjectProtocol?) {
if let object = object as FormObjectProtocol? {
let index = collectionIndexOfObjectInSection(object.rowIdx, itemIndexInSection: object.sectionIdx)
self.displayData.removeAtIndex(index)
self.displayData.insert(object, atIndex: index)
/*
This is an example of optional chaining.
The delegate may or may not exist (an optional), and it may or may not be implementing formValueChanged.
This is what the question marks are delineating.
*/
self.delegate?.formValueChanged?(object)
let indexPath = NSIndexPath(forRow: object.rowIdx, inSection: object.sectionIdx)
if object.reloadOnValueChange == true {
println("\n reloading index at row: \n\n indexPath row: \(indexPath.row) \n indexPath section: \(indexPath.section) \n\n")
tableView.reloadRowsAtIndexPaths([indexPath as NSIndexPath], withRowAnimation: UITableViewRowAnimation.None)
}
//tableView.reloadData()
}
}
/**
Check form objects implementing this method for being valid
:return: An array of validation error strings to be presented however the user wishes.
*/
func validateFormItems(formItemIsValid: FieldNeedsValidation) -> (Bool) {
var isValid = true
var dataThatValidates = data.filter { (filtered: FormObjectProtocol) -> Bool in
filtered.needsValidation == true
}
for protocolObject in dataThatValidates {
if let formIsValid = formItemIsValid(value: protocolObject) as Bool? {
if formIsValid == false {
isValid = false
}
}
}
return isValid
}
/**
Assemble a urlRequest form dictionary.
:return: a urlRequest form dictionary.
*/
func assembleSubmissionDictionary() -> NSDictionary {
var nData = data.filter { (FieldObject) -> Bool in
//Get data which is not being displayed; its value is required and already provided.
FieldObject.displayed == false
}
//Append the display data to nData.
nData += displayData
var filteredData = nData.filter { (T) -> Bool in
var hasKey = false
if let keyAsString = T.key as String? {
if countElements(keyAsString) > 0 {
hasKey = true
}
}
return hasKey == true
}
let mDict: NSMutableDictionary = NSMutableDictionary()
for kV in filteredData {
mDict.setValue(kV.value, forKey: kV.key)
}
return mDict.copy() as NSDictionary
}
/********
private
********/
/**
Compute number of sections for the data.
:return: number of sections for the data.
*/
private func numberOfSections() -> (Int) {
var prevIdx = 0
var mSectionsCount: NSMutableDictionary = NSMutableDictionary()
for data in displayData {
var numSectionsForIdx = mSectionsCount[String(data.sectionIdx)] as Int!
if let sectionsCount = numSectionsForIdx as Int! {
var section = sectionsCount
mSectionsCount.setValue(++section, forKey: String(data.sectionIdx))
} else {
mSectionsCount.setValue(0, forKey: String(data.sectionIdx))
}
++prevIdx
}
return mSectionsCount.allKeys.count
}
func numberOfItemsInSection(section: Int) -> (Int) {
return displayDataForSection(section).count
}
/**
Called in CellForRowAtIndexPath.
:param: FormCell The cell to configure to display its data for the display data for section and row.
:param: NSIndexPath Pretty standard, really.
*/
private func formCellForRowAtIndexPath(cell: UITableViewCell, indexPath: NSIndexPath) {
if let cell = cell as? FormCell {
let displayData = displayDataForSection(indexPath.section)
//A sanity check
if indexPath.row < displayData.count {
var field = displayData[indexPath.row]
requestViewObject(field, cell: cell, {value in
/*
Upon a value change, set the field's value to the new value and replace the current model's object.
*/
field.value = value
self.updateDataModel(field)
})
}
}
}
/**
Filter the display data for the corresponding section.
:param: The section idx.
:returns: Array of
*/
private func displayDataForSection(sectionIdx: Int) -> ([FormObjectProtocol]) {
var dataForSection = displayData.filter { (T) -> Bool in
return T.sectionIdx == sectionIdx
}
dataForSection = dataForSection.sorted { (previous, current) -> Bool in
previous.rowIdx < current.rowIdx
}
return dataForSection
}
/**
Determine the enum then call the associated function, passing an optional UI element. (the cell will create one on its own otherwise)
:param: FormObjectProtocol: an FOP conforming object
:param: FormCell: a form cell
:param: ValueDidChange:
*/
private func requestViewObject(field: FormObjectProtocol, cell: FormCell, valueChangeCallback: FieldDidChange) {
//update the custom field values
if let fieldId = field.identifier as String! {
if fieldId != "" {
customFormObjects.updateValue(field, forKey: fieldId)
println("field added to customFormObjects: \(customFormObjects)")
}
}
let type = UIType(rawValue: field.uiType)
switch type! {
case .TypeNone:
return
case .TypeTextField:
cell.addTextField(delegate?.textFieldForFormObject?(field, aTextField: UITextField()))
case .TypeASwitch:
println("switch value bein set to: \(field.value)")
let aNewSwitch = UISwitch()
aNewSwitch.setOn(field.value as Bool, animated: true)
cell.addSwitch(delegate?.accompanyingLabel?(field, aLabel: UILabel()), aSwitch: delegate?.switchForFormObject?(field, aSwitch: aNewSwitch))
case .TypeCustomView:
cell.addCustomView(delegate?.customViewForFormObject?(field, aView: UIView()))
}
cell.valueDidChange = valueChangeCallback
}
private func collectionIndexOfObjectInSection(section: Int, itemIndexInSection: Int) -> (Int) {
let map = sectionsMap()
var totalCount = 0
for key in map.allKeys {
let count = key.integerValue
let sectionIdx = map[String(key as NSString)] as Int
if sectionIdx < section {
totalCount += count
}
if sectionIdx == section {
totalCount += itemIndexInSection
}
}
return totalCount
}
private func sectionsMap () -> (NSDictionary) {
var prevIdx = 0
var mSectionsCount: NSMutableDictionary = NSMutableDictionary()
for data in displayData {
var numSectionsForIdx = mSectionsCount[String(data.sectionIdx)] as Int!
if let sectionsCount = numSectionsForIdx as Int! {
var section = sectionsCount
mSectionsCount.setValue(++section, forKey: String(data.sectionIdx))
} else {
mSectionsCount.setValue(0, forKey: String(data.sectionIdx))
}
++prevIdx
}
return mSectionsCount.copy() as NSDictionary
}
/*
**************************
tableView delegate methods
**************************
*/
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return numberOfItemsInSection(section) // filteredArrayCount
}
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return numberOfSections()
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: AnyObject? = tableView.dequeueReusableCellWithIdentifier("Cell")
formCellForRowAtIndexPath(cell as UITableViewCell, indexPath: indexPath)
return cell as UITableViewCell
}
public func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var title = ""
if section < sectionHeaderTitles.count {
title = sectionHeaderTitles[section]
}
return title
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let displayData = displayDataForSection(indexPath.section)
//A sanity check
if indexPath.row < displayData.count {
var field = displayData[indexPath.row]
delegate?.didSelectFormObject?(field)
}
}
}
| mit | e3239ec3bfba3381baecc9c8f42110e0 | 28.809055 | 178 | 0.563561 | 5.712184 | false | false | false | false |
EstebanVallejo/sdk-ios | MercadoPagoSDK/MercadoPagoSDK/PromoViewController.swift | 2 | 3829 | //
// PromoViewController.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 22/5/15.
// Copyright (c) 2015 MercadoPago. All rights reserved.
//
import UIKit
import Foundation
public class PromoViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var publicKey : String?
@IBOutlet weak private var tableView : UITableView!
var loadingView : UILoadingView!
var promos : [Promo]!
var bundle : NSBundle? = MercadoPago.getBundle()
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public init(publicKey: String) {
super.init(nibName: "PromoViewController", bundle: self.bundle)
self.publicKey = publicKey
}
public init() {
super.init(nibName: "PromoViewController", bundle: self.bundle)
}
override public init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
override public func viewDidLoad() {
super.viewDidLoad()
self.title = "Promociones".localized
self.navigationItem.backBarButtonItem = UIBarButtonItem(title: "Atrás", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
self.tableView.registerNib(UINib(nibName: "PromoTableViewCell", bundle: self.bundle), forCellReuseIdentifier: "PromoTableViewCell")
self.tableView.registerNib(UINib(nibName: "PromosTyCTableViewCell", bundle: self.bundle), forCellReuseIdentifier: "PromosTyCTableViewCell")
self.tableView.registerNib(UINib(nibName: "PromoEmptyTableViewCell", bundle: self.bundle), forCellReuseIdentifier: "PromoEmptyTableViewCell")
self.tableView.estimatedRowHeight = 44.0
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.delegate = self
self.tableView.dataSource = self
self.loadingView = UILoadingView(frame: MercadoPago.screenBoundsFixedToPortraitOrientation(), text: "Cargando...".localized)
self.view.addSubview(self.loadingView)
var mercadoPago : MercadoPago
mercadoPago = MercadoPago(keyType: MercadoPago.PUBLIC_KEY, key: self.publicKey)
mercadoPago.getPromos({ (promos) -> Void in
self.promos = promos
self.tableView.reloadData()
self.loadingView.removeFromSuperview()
}, failure: { (error) -> Void in
if error.code == MercadoPago.ERROR_API_CODE {
self.tableView.reloadData()
self.loadingView.removeFromSuperview()
}
})
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return promos == nil ? 1 : promos.count + 1
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if self.promos != nil && self.promos.count > 0 {
if indexPath.row < self.promos.count {
var promoCell : PromoTableViewCell = tableView.dequeueReusableCellWithIdentifier("PromoTableViewCell", forIndexPath: indexPath) as! PromoTableViewCell
promoCell.setPromoInfo(self.promos[indexPath.row])
return promoCell
} else {
return tableView.dequeueReusableCellWithIdentifier("PromosTyCTableViewCell", forIndexPath: indexPath) as! PromosTyCTableViewCell
}
} else {
return tableView.dequeueReusableCellWithIdentifier("PromoEmptyTableViewCell", forIndexPath: indexPath) as! PromoEmptyTableViewCell
}
}
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if self.promos != nil && self.promos.count > 0 {
if indexPath.row == self.promos.count {
return 55
} else {
return 151
}
} else {
return 80
}
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.row == self.promos.count {
self.navigationController?.pushViewController(PromosTyCViewController(promos: self.promos), animated: true)
}
}
}
| mit | a60a102e0cfe88b2cc94d818109b79aa | 33.178571 | 154 | 0.751306 | 4.125 | false | false | false | false |
philipgreat/b2b-swift-app | B2BSimpleApp/B2BSimpleApp/Brand.swift | 1 | 2007 | //Domain B2B/Brand/
import Foundation
import ObjectMapper //Use this to generate Object
import SwiftyJSON //Use this to verify the JSON Object
struct Brand{
var id : String?
var brandName : String?
var logo : String?
var remark : String?
var version : Int?
var productList : [Product]?
init(){
//lazy load for all the properties
//This is good for UI applications as it might saves RAM which is very expensive in mobile devices
}
static var CLASS_VERSION = "1"
//This value is for serializer like message pack to identify the versions match between
//local and remote object.
}
extension Brand: Mappable{
//Confirming to the protocol Mappable of ObjectMapper
//Reference on https://github.com/Hearst-DD/ObjectMapper/
init?(_ map: Map){
}
mutating func mapping(map: Map) {
//Map each field to json fields
id <- map["id"]
brandName <- map["brandName"]
logo <- map["logo"]
remark <- map["remark"]
version <- map["version"]
productList <- map["productList"]
}
}
extension Brand:CustomStringConvertible{
//Confirming to the protocol CustomStringConvertible of Foundation
var description: String{
//Need to find out a way to improve this method performance as this method might called to
//debug or log, using + is faster than \(var).
var result = "brand{";
if id != nil {
result += "\tid='\(id!)'"
}
if brandName != nil {
result += "\tbrand_name='\(brandName!)'"
}
if logo != nil {
result += "\tlogo='\(logo!)'"
}
if remark != nil {
result += "\tremark='\(remark!)'"
}
if version != nil {
result += "\tversion='\(version!)'"
}
result += "}"
return result
}
}
| mit | f38d4382c7dd949240825e66568156ae | 21.068966 | 100 | 0.54858 | 3.772556 | false | false | false | false |
PureSwift/SeeURL | Sources/SeeURL/cURLReadFunction.swift | 2 | 1210 | //
// cURLReadFunction.swift
// SwiftFoundation
//
// Created by Alsey Coleman Miller on 8/4/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
#if os(Linux)
import CcURL
#endif
import SwiftFoundation
public extension cURL {
public typealias ReadCallBack = curl_read_callback
public static var ReadFunction: ReadCallBack { return curlReadFunction }
public final class ReadFunctionStorage {
public let data: Data
public var currentIndex = 0
public init(data: Data) {
self.data = data
}
}
}
public func curlReadFunction(pointer: UnsafeMutablePointer<Int8>, size: Int, nmemb: Int, readData: UnsafeMutablePointer<Void>) -> Int {
let storage = unsafeBitCast(readData, cURL.ReadFunctionStorage.self)
let data = storage.data
let currentIndex = storage.currentIndex
guard (size * nmemb) > 0 else { return 0 }
guard currentIndex < data.byteValue.count else { return 0 }
let byte = data.byteValue[currentIndex]
let char = CChar(byte)
pointer.memory = char
storage.currentIndex += 1
return 1
}
| mit | b207eac3d93c8e730505492dcb7cc575 | 20.589286 | 135 | 0.630273 | 4.579545 | false | false | false | false |
benlangmuir/swift | stdlib/public/core/DurationProtocol.swift | 9 | 1247 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that defines a duration for a given `InstantProtocol` type.
@available(SwiftStdlib 5.7, *)
public protocol DurationProtocol: Comparable, AdditiveArithmetic, Sendable {
static func / (_ lhs: Self, _ rhs: Int) -> Self
static func /= (_ lhs: inout Self, _ rhs: Int)
static func * (_ lhs: Self, _ rhs: Int) -> Self
static func *= (_ lhs: inout Self, _ rhs: Int)
static func / (_ lhs: Self, _ rhs: Self) -> Double
}
@available(SwiftStdlib 5.7, *)
extension DurationProtocol {
@available(SwiftStdlib 5.7, *)
public static func /= (_ lhs: inout Self, _ rhs: Int) {
lhs = lhs / rhs
}
@available(SwiftStdlib 5.7, *)
public static func *= (_ lhs: inout Self, _ rhs: Int) {
lhs = lhs * rhs
}
}
| apache-2.0 | 01a2f011fbcff158724d2f6e05fbc875 | 34.628571 | 80 | 0.580593 | 4.156667 | false | false | false | false |
benlangmuir/swift | test/SourceKit/VariableType/basic.swift | 11 | 874 | let x: Int = 3
let y = "abc"
var foo = ["abc" + "def"]
struct A {
let x: String = ""
let y = ""
}
class B {
var x = 4.0
var y = [A]()
var z: [Int: Int] = [:]
var w: (Int) -> Int { { $0 * 2 } }
}
func foo() {
var local = 5
}
let `else` = 3
// RUN: %sourcekitd-test -req=collect-var-type %s -- %s | %FileCheck %s
// CHECK: (1:5, 1:6): Int (explicit type: 1)
// CHECK: (2:5, 2:6): String (explicit type: 0)
// CHECK: (4:5, 4:8): [String] (explicit type: 0)
// CHECK: (7:7, 7:8): String (explicit type: 1)
// CHECK: (8:7, 8:8): String (explicit type: 0)
// CHECK: (12:7, 12:8): Double (explicit type: 0)
// CHECK: (13:7, 13:8): [A] (explicit type: 0)
// CHECK: (14:7, 14:8): [Int : Int] (explicit type: 1)
// CHECK: (15:7, 15:8): (Int) -> Int (explicit type: 1)
// CHECK: (19:7, 19:12): Int (explicit type: 0)
// CHECK: (22:5, 22:11): Int (explicit type: 0)
| apache-2.0 | 27db77a787b44d32ab72a6f8e99f01e5 | 23.971429 | 71 | 0.532037 | 2.336898 | false | false | false | false |
apple/swift-numerics | Sources/RealModule/ElementaryFunctions.swift | 1 | 8972 | //===--- ElementaryFunctions.swift ----------------------------*- swift -*-===//
//
// This source file is part of the Swift Numerics open source project
//
// Copyright (c) 2019 Apple Inc. and the Swift Numerics project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// A type that has elementary functions available.
///
/// An ["elementary function"][elfn] is a function built up from powers, roots,
/// exponentials, logarithms, trigonometric functions (sin, cos, tan) and
/// their inverses, and the hyperbolic functions (sinh, cosh, tanh) and their
/// inverses.
///
/// Conformance to this protocol means that all of these building blocks are
/// available as static functions on the type.
///
/// ```swift
/// let x: Float = 1
/// let y = Float.sin(x) // 0.84147096
/// ```
///
/// There are three broad families of functions defined by
/// `ElementaryFunctions`:
/// - Exponential, trigonometric, and hyperbolic functions:
/// `exp`, `expMinusOne`, `cos`, `sin`, `tan`, `cosh`, `sinh`, and `tanh`.
/// - Logarithmic, inverse trigonometric, and inverse hyperbolic functions:
/// `log`, `log(onePlus:)`, `acos`, `asin`, `atan`, `acosh`, `asinh`, and
/// `atanh`.
/// - Power and root functions:
/// `pow`, `sqrt`, and `root`.
///
/// `ElementaryFunctions` conformance implies `AdditiveArithmetic`, so addition
/// and subtraction and the `.zero` property are also available.
///
/// There are two other protocols that you are more likely to want to use
/// directly:
///
/// `RealFunctions` refines `ElementaryFunctions` and includes
/// additional functions specific to real number types.
///
/// `Real` conforms to `RealFunctions` and `FloatingPoint`, and is the
/// protocol that you will want to use most often for generic code.
///
/// See Also:
///
/// - `RealFunctions`
/// - `Real`
///
/// [elfn]: http://en.wikipedia.org/wiki/Elementary_function
public protocol ElementaryFunctions: AdditiveArithmetic {
/// The [exponential function][wiki] e^x whose base `e` is the base of the
/// natural logarithm.
///
/// See also `expMinusOne()`, as well as `exp2()` and `exp10()`
/// defined for types conforming to `RealFunctions`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Exponential_function
static func exp(_ x: Self) -> Self
/// exp(x) - 1, computed in such a way as to maintain accuracy for small x.
///
/// When `x` is close to zero, the expression `.exp(x) - 1` suffers from
/// catastrophic cancellation and the result will not have full accuracy.
/// The `.expMinusOne(x)` function gives you a means to address this problem.
///
/// As an example, consider the expression `(x + 1)*exp(x) - 1`. When `x`
/// is smaller than `.ulpOfOne`, this expression evaluates to `0.0`, when it
/// should actually round to `2*x`. We can get a full-accuracy result by
/// using the following instead:
/// ```
/// let t = .expMinusOne(x)
/// return x*(t+1) + t // x*exp(x) + (exp(x)-1) = (x+1)*exp(x) - 1
/// ```
/// This re-written expression delivers an accurate result for all values
/// of `x`, not just for small values.
///
/// See also `exp()`, as well as `exp2()` and `exp10()` defined for types
/// conforming to `RealFunctions`.
static func expMinusOne(_ x: Self) -> Self
/// The [hyperbolic cosine][wiki] of `x`.
/// ```
/// e^x + e^-x
/// cosh(x) = ------------
/// 2
/// ```
///
/// See also `sinh()`, `tanh()` and `acosh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
static func cosh(_ x: Self) -> Self
/// The [hyperbolic sine][wiki] of `x`.
/// ```
/// e^x - e^-x
/// sinh(x) = ------------
/// 2
/// ```
///
/// See also `cosh()`, `tanh()` and `asinh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
static func sinh(_ x: Self) -> Self
/// The [hyperbolic tangent][wiki] of `x`.
/// ```
/// sinh(x)
/// tanh(x) = ---------
/// cosh(x)
/// ```
///
/// See also `cosh()`, `sinh()` and `atanh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Hyperbolic_function
static func tanh(_ x: Self) -> Self
/// The [cosine][wiki] of `x`.
///
/// For real types, `x` may be interpreted as an angle measured in radians.
///
/// See also `sin()`, `tan()` and `acos()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Cosine
static func cos(_ x: Self) -> Self
/// The [sine][wiki] of `x`.
///
/// For real types, `x` may be interpreted as an angle measured in radians.
///
/// See also `cos()`, `tan()` and `asin()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Sine
static func sin(_ x: Self) -> Self
/// The [tangent][wiki] of `x`.
///
/// For real types, `x` may be interpreted as an angle measured in radians.
///
/// See also `cos()`, `sin()` and `atan()`, as well as `atan2(y:x:)` for
/// types that conform to `RealFunctions`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Tangent
static func tan(_ x: Self) -> Self
/// The [natural logarithm][wiki] of `x`.
///
/// See also `log(onePlus:)`, as well as `log2()` and `log10()` for types
/// that conform to `RealFunctions`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Logarithm
static func log(_ x: Self) -> Self
/// log(1 + x), computed in such a way as to maintain accuracy for small x.
///
/// See also `log()`, as well as `log2()` and `log10()` for types
/// that conform to `RealFunctions`.
static func log(onePlus x: Self) -> Self
/// The [inverse hyperbolic cosine][wiki] of `x`.
/// ```
/// cosh(acosh(x)) ≅ x
/// ```
/// See also `asinh()`, `atanh()` and `cosh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
static func acosh(_ x: Self) -> Self
/// The [inverse hyperbolic sine][wiki] of `x`.
/// ```
/// sinh(asinh(x)) ≅ x
/// ```
/// See also `acosh()`, `atanh()` and `sinh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
static func asinh(_ x: Self) -> Self
/// The [inverse hyperbolic tangent][wiki] of `x`.
/// ```
/// tanh(atanh(x)) ≅ x
/// ```
/// See also `acosh()`, `asinh()` and `tanh()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_hyperbolic_function
static func atanh(_ x: Self) -> Self
/// The [arccosine][wiki] (inverse cosine) of `x`.
///
/// For real types, the result may be interpreted as an angle measured in
/// radians.
/// ```
/// cos(acos(x)) ≅ x
/// ```
/// See also `asin()`, `atan()` and `cos()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
static func acos(_ x: Self) -> Self
/// The [arcsine][wiki] (inverse sine) of `x`.
///
/// For real types, the result may be interpreted as an angle measured in
/// radians.
/// ```
/// sin(asin(x)) ≅ x
/// ```
/// See also `acos()`, `atan()` and `sin()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
static func asin(_ x: Self) -> Self
/// The [arctangent][wiki] (inverse tangent) of `x`.
///
/// For real types, the result may be interpreted as an angle measured in
/// radians.
/// ```
/// tan(atan(x)) ≅ x
/// ```
/// See also `acos()`, `asin()` and `tan()`, as well as `atan2(y:x:)` for
/// types that conform to `RealArithmetic`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Inverse_trigonometric_functions
static func atan(_ x: Self) -> Self
/// exp(y * log(x)) computed with additional internal precision.
///
/// The edge-cases of this function are defined based on the behavior of the
/// expression `exp(y log x)`, matching IEEE 754's `powr` operation.
/// In particular, this means that if `x` and `y` are both zero, `pow(x,y)`
/// is `nan` for real types and `infinity` for complex types, rather than 1.
///
/// There is also a `pow(_:Self,_:Int)` overload, whose behavior is defined
/// in terms of repeated multiplication, and hence returns 1 for this case.
///
/// See also `sqrt()` and `root()`.
static func pow(_ x: Self, _ y: Self) -> Self
/// `x` raised to the nth power.
///
/// The edge-cases of this function are defined in terms of repeated
/// multiplication or division, rather than exp(n log x). In particular,
/// `Float.pow(0, 0)` is 1.
///
/// See also `sqrt()` and `root()`.
static func pow(_ x: Self, _ n: Int) -> Self
/// The [square root][wiki] of `x`.
///
/// See also `pow()` and `root()`.
///
/// [wiki]: https://en.wikipedia.org/wiki/Square_root
static func sqrt(_ x: Self) -> Self
/// The nth root of `x`.
///
/// See also `pow()` and `sqrt()`.
static func root(_ x: Self, _ n: Int) -> Self
}
| apache-2.0 | 58ded39cfc10410b4db049916579575f | 33.198473 | 80 | 0.581585 | 3.586869 | false | false | false | false |
sharplet/five-day-plan | Tests/FiveDayPlanTests/Models/PlanTemplateSpec.swift | 1 | 1728 | @testable import FiveDayPlan
import Quick
import Nimble
final class PlanTemplateSpec: QuickSpec {
override func spec() {
let testTemplate = { try PlanTemplate(name: "test", bundle: testBundle) }
describe("loading") {
it("loads from a text file") {
expect { try testTemplate() }.toNot(throwError())
}
it("fails to load if the text file doesn't exist") {
let nonexistent = { try PlanTemplate(name: "nonexistent", bundle: testBundle) }
expect { try nonexistent() }.to(throwError())
}
}
describe("parsing") {
it("extracts the first line as the week title") {
let title = { try testTemplate().weeks.first?.title }
expect { try title() } == "Test Week 1"
}
it("extracts multiple weeks separated by empty lines") {
let titles = { try testTemplate().weeks.map { $0.title } }
expect { try titles() } == ["Test Week 1", "Test Week 2", "Test Week 3"]
}
it("parses each line as a scripture collection for that day") {
let chapters = { try testTemplate().weeks.first?.days.first?.chapters }
expect { try chapters()?.at(0)?.description } == "Genesis 1"
expect { try chapters()?.at(1)?.description } == "Proverbs 1"
expect { try chapters()?.at(2)?.description } == "Proverbs 2"
expect { try chapters()?.at(3)?.description } == "Proverbs 3"
expect { try chapters()?.at(4)?.description } == "Mark 1"
expect { try chapters()?.at(5)?.description } == "Mark 2"
expect { try chapters()?.at(6)?.description } == "Titus"
}
}
describe("2017") {
it("exists") {
expect(PlanTemplate.year2017).toNot(beNil())
}
}
}
}
| mit | 72a38ba9cc999d68caae60987e770412 | 34.265306 | 87 | 0.586227 | 4 | false | true | false | false |
cuba/NetworkKit | Source/Response/Response.swift | 1 | 1519 | //
// ResponseInterface.swift
// NetworkKit iOS
//
// Created by Jacob Sikorski on 2019-02-21.
// Copyright © 2019 Jacob Sikorski. All rights reserved.
//
import Foundation
/// The protocol wrapping the response object.
public protocol ResponseInterface {
associatedtype T
var data: T { get }
var httpResponse: HTTPURLResponse { get }
var urlRequest: URLRequest { get }
var statusCode: StatusCode { get }
}
/// A successful response object. This is retuned when there is any 2xx response.
public struct Response<T>: ResponseInterface {
public let data: T
public let httpResponse: HTTPURLResponse
public let urlRequest: URLRequest
public let statusCode: StatusCode
/// Handles common errors like 4xx and 5xx errors.
/// Network related errors are handled directly in
/// The error callback.
public let error: ResponseError?
/// Create a successful response object.
///
/// - Parameters:
/// - data: The data object to return.
/// - httpResponse: The `HTTPURLresponse` that is returned.
/// - urlRequest: The original `URLRequest` that was created.
/// - statusCode: The status code enum that is returned.
public init(data: T, httpResponse: HTTPURLResponse, urlRequest: URLRequest, statusCode: StatusCode, error: ResponseError?) {
self.data = data
self.httpResponse = httpResponse
self.urlRequest = urlRequest
self.statusCode = statusCode
self.error = error
}
}
| mit | 081939e02b10ae3d85fec97d548829c5 | 31.297872 | 128 | 0.679842 | 4.656442 | false | false | false | false |
bsantanas/Twitternator2 | Twitternator2/Swifter/Swifter.swift | 8 | 8242 | //
// Swifter.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// 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 Accounts
public class Swifter {
// MARK: - Types
public typealias JSONSuccessHandler = (json: JSON, response: NSHTTPURLResponse) -> Void
public typealias FailureHandler = (error: NSError) -> Void
internal struct CallbackNotification {
static let notificationName = "SwifterCallbackNotificationName"
static let optionsURLKey = "SwifterCallbackNotificationOptionsURLKey"
}
internal struct SwifterError {
static let domain = "SwifterErrorDomain"
static let appOnlyAuthenticationErrorCode = 1
}
internal struct DataParameters {
static let dataKey = "SwifterDataParameterKey"
static let fileNameKey = "SwifterDataParameterFilename"
}
// MARK: - Properties
internal(set) var apiURL: NSURL
internal(set) var uploadURL: NSURL
internal(set) var streamURL: NSURL
internal(set) var userStreamURL: NSURL
internal(set) var siteStreamURL: NSURL
public var client: SwifterClientProtocol
// MARK: - Initializers
public convenience init(consumerKey: String, consumerSecret: String) {
self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, appOnly: false)
}
public init(consumerKey: String, consumerSecret: String, appOnly: Bool) {
if appOnly {
self.client = SwifterAppOnlyClient(consumerKey: consumerKey, consumerSecret: consumerSecret)
}
else {
self.client = SwifterOAuthClient(consumerKey: consumerKey, consumerSecret: consumerSecret)
}
self.apiURL = NSURL(string: "https://api.twitter.com/1.1/")!
self.uploadURL = NSURL(string: "https://upload.twitter.com/1.1/")!
self.streamURL = NSURL(string: "https://stream.twitter.com/1.1/")!
self.userStreamURL = NSURL(string: "https://userstream.twitter.com/1.1/")!
self.siteStreamURL = NSURL(string: "https://sitestream.twitter.com/1.1/")!
}
public init(consumerKey: String, consumerSecret: String, oauthToken: String, oauthTokenSecret: String) {
self.client = SwifterOAuthClient(consumerKey: consumerKey, consumerSecret: consumerSecret , accessToken: oauthToken, accessTokenSecret: oauthTokenSecret)
self.apiURL = NSURL(string: "https://api.twitter.com/1.1/")!
self.uploadURL = NSURL(string: "https://upload.twitter.com/1.1/")!
self.streamURL = NSURL(string: "https://stream.twitter.com/1.1/")!
self.userStreamURL = NSURL(string: "https://userstream.twitter.com/1.1/")!
self.siteStreamURL = NSURL(string: "https://sitestream.twitter.com/1.1/")!
}
public init(account: ACAccount) {
self.client = SwifterAccountsClient(account: account)
self.apiURL = NSURL(string: "https://api.twitter.com/1.1/")!
self.uploadURL = NSURL(string: "https://upload.twitter.com/1.1/")!
self.streamURL = NSURL(string: "https://stream.twitter.com/1.1/")!
self.userStreamURL = NSURL(string: "https://userstream.twitter.com/1.1/")!
self.siteStreamURL = NSURL(string: "https://sitestream.twitter.com/1.1/")!
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - JSON Requests
internal func jsonRequestWithPath(path: String, baseURL: NSURL, method: String, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler? = nil, downloadProgress: JSONSuccessHandler? = nil, success: JSONSuccessHandler? = nil, failure: SwifterHTTPRequest.FailureHandler? = nil) -> SwifterHTTPRequest {
let jsonDownloadProgressHandler: SwifterHTTPRequest.DownloadProgressHandler = {
data, _, _, response in
if downloadProgress == nil {
return
}
var error: NSError?
if let jsonResult = JSON.parseJSONData(data, error: &error) {
downloadProgress?(json: jsonResult, response: response)
}
else {
let jsonString = NSString(data: data, encoding: NSUTF8StringEncoding)
let jsonChunks = jsonString!.componentsSeparatedByString("\r\n") as! [String]
for chunk in jsonChunks {
if count(chunk.utf16) == 0 {
continue
}
let chunkData = chunk.dataUsingEncoding(NSUTF8StringEncoding)
if let jsonResult = JSON.parseJSONData(data, error: &error) {
if let downloadProgress = downloadProgress {
downloadProgress(json: jsonResult, response: response)
}
}
}
}
}
let jsonSuccessHandler: SwifterHTTPRequest.SuccessHandler = {
data, response in
dispatch_async(dispatch_get_global_queue(QOS_CLASS_UTILITY, 0)) {
var error: NSError?
if let jsonResult = JSON.parseJSONData(data, error: &error) {
dispatch_async(dispatch_get_main_queue()) {
if let success = success {
success(json: jsonResult, response: response)
}
}
}
else {
dispatch_async(dispatch_get_main_queue()) {
if let failure = failure {
failure(error: error!)
}
}
}
}
}
if method == "GET" {
return self.client.get(path, baseURL: baseURL, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: jsonDownloadProgressHandler, success: jsonSuccessHandler, failure: failure)
}
else {
return self.client.post(path, baseURL: baseURL, parameters: parameters, uploadProgress: uploadProgress, downloadProgress: jsonDownloadProgressHandler, success: jsonSuccessHandler, failure: failure)
}
}
internal func getJSONWithPath(path: String, baseURL: NSURL, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: JSONSuccessHandler?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest {
return self.jsonRequestWithPath(path, baseURL: baseURL, method: "GET", parameters: parameters, uploadProgress: uploadProgress, downloadProgress: downloadProgress, success: success, failure: failure)
}
internal func postJSONWithPath(path: String, baseURL: NSURL, parameters: Dictionary<String, Any>, uploadProgress: SwifterHTTPRequest.UploadProgressHandler?, downloadProgress: JSONSuccessHandler?, success: JSONSuccessHandler?, failure: SwifterHTTPRequest.FailureHandler?) -> SwifterHTTPRequest {
return self.jsonRequestWithPath(path, baseURL: baseURL, method: "POST", parameters: parameters, uploadProgress: uploadProgress, downloadProgress: downloadProgress, success: success, failure: failure)
}
}
| mit | 78c05f012ca18b55873efeb876fe546a | 45.303371 | 341 | 0.659063 | 4.938286 | false | false | false | false |
bricklife/JSONRPCKit | Sources/JSONRPCKit/JSONRPCError.swift | 1 | 1432 | //
// JSONRPCError.swift
// JSONRPCKit
//
// Created by Shinichiro Oba on 2015/11/09.
// Copyright © 2015年 Shinichiro Oba. All rights reserved.
//
import Foundation
public enum JSONRPCError: Error {
case responseError(code: Int, message: String, data: Any?)
case responseNotFound(requestId: Id?, object: Any)
case resultObjectParseError(Error)
case errorObjectParseError(Error)
case unsupportedVersion(String?)
case unexpectedTypeObject(Any)
case missingBothResultAndError(Any)
case nonArrayResponse(Any)
public init(errorObject: Any) {
enum ParseError: Error {
case nonDictionaryObject(object: Any)
case missingKey(key: String, errorObject: Any)
}
do {
guard let dictionary = errorObject as? [String: Any] else {
throw ParseError.nonDictionaryObject(object: errorObject)
}
guard let code = dictionary["code"] as? Int else {
throw ParseError.missingKey(key: "code", errorObject: errorObject)
}
guard let message = dictionary["message"] as? String else {
throw ParseError.missingKey(key: "message", errorObject: errorObject)
}
self = .responseError(code: code, message: message, data: dictionary["data"])
} catch {
self = .errorObjectParseError(error)
}
}
}
| mit | 8796a5cd92f2c7053e67f4882b5fd90d | 30.065217 | 89 | 0.624213 | 4.437888 | false | false | false | false |
tickCoder/Practise_Swift | Practise_Swift/Protocols_and_Extensions.swift | 1 | 2481 | //
// Protocols_and_Extensions.swift
// Practise_Swift
//
// Created by Click on 2015.11.05.Thursday.
// Copyright © 2015 tickCoder. All rights reserved.
//
import Foundation
protocol ExampleProtocol {
var simpleDescription: String {
get
}
mutating func adjust()
}
/*
类,枚举,结构体都可以遵从协议
*/
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "a vary simple class"
var anotherProperty: Int = 69105
func adjust() {
simpleDescription += " Now 100% adjusted"
}
}
/*
class不需声明mutating,因为class里面的函数始终可以修改这个class
*/
struct SimpleStructure: ExampleProtocol {
var simpleDescription: String = "a simple structure"
mutating func adjust() {
simpleDescription += " (adjusted)"
}
}
////???报错
//enum SimpleEnumeration: ExampleProtocol {
// var simpleDescription: String = "a Simple Structure"
// mutating func adjust() {
// simpleDescription += " adjusted"
// }
//}
/*
使用extension向已存在的类型添加函数功能,如一个心函数或者computed properties。
可以使用extension向存在于其他地方的类型添加protocol,甚至是引用自的framework库
*/
extension Int:ExampleProtocol {
var simpleDescription: String {
return "The Number \(self)"
}
mutating func adjust() {
self += 42
}
}
class Protocols_Extensions_Test {
func test() {
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
print(aDescription)
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
print(bDescription)
print(7.simpleDescription)
/*
你可以像使用其他名称类型一样使用protocol名称,比如创建一个拥有不同类型、但都遵守同一协议的对象的集合。
当你使用类型为protocol类型的值时,protcol定义之外的函数是不可用的
*/
let protocolValue: ExampleProtocol = a
print(protocolValue.simpleDescription)
//print(protocolValue.anotherProperty)//报错(虽然protocolValue是SimpleClass类型,但是编译器将它以ExampleProtocol类型对待。所以你不能突然访问SimpleClass在protocol之外的函数或属性,也就是它访问不到a.anotherProperty的)
}
} | mit | 29d1c38d439a5feb0224c3c9b1862e8c | 20.882979 | 174 | 0.657101 | 3.938697 | false | false | false | false |
OscarSwanros/swift | test/SILGen/objc_imported_generic.swift | 2 | 8541 | // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-silgen %s -enable-sil-ownership | %FileCheck %s
// For integration testing, ensure we get through IRGen too.
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -emit-ir -verify -DIRGEN_INTEGRATION_TEST %s
// REQUIRES: objc_interop
import objc_generics
func callInitializer() {
_ = GenericClass(thing: NSObject())
}
// CHECK-LABEL: sil shared [serializable] @_T0So12GenericClassCSQyAByxGGSQyxG5thing_tcfC
// CHECK: thick_to_objc_metatype {{%.*}} : $@thick GenericClass<T>.Type to $@objc_metatype GenericClass<T>.Type
public func genericMethodOnAnyObject(o: AnyObject, b: Bool) -> AnyObject {
return o.thing!()!
}
// CHECK-LABEL: sil @_T021objc_imported_generic0C17MethodOnAnyObject{{[_0-9a-zA-Z]*}}F
// CHECK: objc_method {{%.*}} : $@opened([[TAG:.*]]) AnyObject, #GenericClass.thing!1.foreign : <T where T : AnyObject> (GenericClass<T>) -> () -> T?, $@convention(objc_method) @pseudogeneric (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>
public func genericMethodOnAnyObjectChained(o: AnyObject, b: Bool) -> AnyObject? {
return o.thing?()
}
// CHECK-LABEL: sil @_T021objc_imported_generic0C24MethodOnAnyObjectChainedyXlSgyXl1o_Sb1btF
// CHECK: bb0([[ANY:%.*]] : @owned $AnyObject, [[BOOL:%.*]] : @trivial $Bool):
// CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.thing!1.foreign, bb1
// CHECK: bb1({{%.*}} : @trivial $@convention(objc_method) @pseudogeneric (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>):
// CHECK: } // end sil function '_T021objc_imported_generic0C24MethodOnAnyObjectChainedyXlSgyXl1o_Sb1btF'
public func genericSubscriptOnAnyObject(o: AnyObject, b: Bool) -> AnyObject? {
return o[0 as UInt16]
}
// CHECK-LABEL: sil @_T021objc_imported_generic0C20SubscriptOnAnyObjectyXlSgyXl1o_Sb1btF
// CHECK: bb0([[ANY:%.*]]
// CHCEK: [[OPENED_ANY:%.*]] = open_existential_ref [[ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.subscript!getter.1.foreign, bb1
// CHECK: bb1({{%.*}} : @trivial $@convention(objc_method) @pseudogeneric (UInt16, @opened([[TAG]]) AnyObject) -> @autoreleased AnyObject):
// CHECK: } // end sil function '_T021objc_imported_generic0C20SubscriptOnAnyObjectyXlSgyXl1o_Sb1btF'
public func genericPropertyOnAnyObject(o: AnyObject, b: Bool) -> AnyObject?? {
return o.propertyThing
}
// CHECK-LABEL: sil @_T021objc_imported_generic0C19PropertyOnAnyObjectyXlSgSgyXl1o_Sb1btF
// CHECK: bb0([[ANY:%.*]] : @owned $AnyObject, [[BOOL:%.*]] : @trivial $Bool):
// CHECK: [[BORROWED_ANY:%.*]] = begin_borrow [[ANY]]
// CHECK: [[OPENED_ANY:%.*]] = open_existential_ref [[BORROWED_ANY]]
// CHECK: [[OPENED_ANY_COPY:%.*]] = copy_value [[OPENED_ANY]]
// CHECK: dynamic_method_br [[OPENED_ANY_COPY]] : $@opened([[TAG:.*]]) AnyObject, #GenericClass.propertyThing!getter.1.foreign, bb1
// CHECK: bb1({{%.*}} : @trivial $@convention(objc_method) @pseudogeneric (@opened([[TAG]]) AnyObject) -> @autoreleased Optional<AnyObject>):
// CHECK: } // end sil function '_T021objc_imported_generic0C19PropertyOnAnyObjectyXlSgSgyXl1o_Sb1btF'
public protocol ThingHolder {
associatedtype Thing
init!(thing: Thing!)
func thing() -> Thing?
func arrayOfThings() -> [Thing]
func setArrayOfThings(_: [Thing])
static func classThing() -> Thing?
var propertyThing: Thing? { get set }
var propertyArrayOfThings: [Thing]? { get set }
}
// TODO: Crashes in IRGen because the type metadata for `T` is not found in
// the witness thunk to satisfy the associated type requirement. This could be
// addressed by teaching IRGen to fulfill erased type parameters from protocol
// witness tables (rdar://problem/26602097).
#if !IRGEN_INTEGRATION_TEST
extension GenericClass: ThingHolder {}
#endif
public protocol Ansible: class {
associatedtype Anser: ThingHolder
}
public func genericBlockBridging<T: Ansible>(x: GenericClass<T>) {
let block = x.blockForPerformingOnThings()
x.performBlock(onThings: block)
}
// CHECK-LABEL: sil @_T021objc_imported_generic0C13BlockBridging{{[_0-9a-zA-Z]*}}F
// CHECK: [[BLOCK_TO_FUNC:%.*]] = function_ref @_T0xxIeyBya_xxIexxo_21objc_imported_generic7AnsibleRzlTR
// CHECK: partial_apply [[BLOCK_TO_FUNC]]<T>
// CHECK: [[FUNC_TO_BLOCK:%.*]] = function_ref @_T0xxIexxo_xxIeyBya_21objc_imported_generic7AnsibleRzlTR
// CHECK: init_block_storage_header {{.*}} invoke [[FUNC_TO_BLOCK]]<T>
// CHECK-LABEL: sil @_T021objc_imported_generic20arraysOfGenericParam{{[_0-9a-zA-Z]*}}F
public func arraysOfGenericParam<T: AnyObject>(y: Array<T>) {
// CHECK: function_ref {{@_T0So12GenericClassCSQyAByxGGSayxG13arrayOfThings.*}} : $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@owned Array<τ_0_0>, @thick GenericClass<τ_0_0>.Type) -> @owned Optional<GenericClass<τ_0_0>>
let x = GenericClass<T>(arrayOfThings: y)!
// CHECK: objc_method {{%.*}} : $GenericClass<T>, #GenericClass.setArrayOfThings!1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, GenericClass<τ_0_0>) -> ()
x.setArrayOfThings(y)
// CHECK: objc_method {{%.*}} : $GenericClass<T>, #GenericClass.propertyArrayOfThings!getter.1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (GenericClass<τ_0_0>) -> @autoreleased Optional<NSArray>
_ = x.propertyArrayOfThings
// CHECK: objc_method {{%.*}} : $GenericClass<T>, #GenericClass.propertyArrayOfThings!setter.1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (Optional<NSArray>, GenericClass<τ_0_0>) -> ()
x.propertyArrayOfThings = y
}
// CHECK-LABEL: sil private @_T021objc_imported_generic0C4FuncyxmRlzClFyycfU_ : $@convention(thin) <V where V : AnyObject> () -> () {
// CHECK: [[INIT:%.*]] = function_ref @_T0So12GenericClassCAByxGycfC : $@convention(method) <τ_0_0 where τ_0_0 : AnyObject> (@thick GenericClass<τ_0_0>.Type) -> @owned GenericClass<τ_0_0>
// CHECK: [[META:%.*]] = metatype $@thick GenericClass<V>.Type
// CHECK: apply [[INIT]]<V>([[META]])
// CHECK: return
func genericFunc<V: AnyObject>(_ v: V.Type) {
let _ = {
var _ = GenericClass<V>()
}
}
// CHECK-LABEL: sil hidden @_T021objc_imported_generic23configureWithoutOptionsyyF : $@convention(thin) () -> ()
// CHECK: [[NIL_FN:%.*]] = function_ref @_T0SqxSgyt10nilLiteral_tcfC : $@convention(method) <τ_0_0> (@thin Optional<τ_0_0>.Type) -> @out Optional<τ_0_0>
// CHECK: apply [[NIL_FN]]<[GenericOption : Any]>({{.*}})
// CHECK: return
func configureWithoutOptions() {
_ = GenericClass<NSObject>(options: nil)
}
// foreign to native thunk for init(options:), uses GenericOption : Hashable
// conformance
// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So12GenericClassCSQyAByxGGs10DictionaryVySC0A6OptionVypGSg7options_tcfcTO : $@convention(method) <T where T : AnyObject> (@owned Optional<Dictionary<GenericOption, Any>>, @owned GenericClass<T>) -> @owned Optional<GenericClass<T>>
// CHECK: [[FN:%.*]] = function_ref @_T0s10DictionaryV10FoundationE19_bridgeToObjectiveCSo12NSDictionaryCyF : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
// CHECK: apply [[FN]]<GenericOption, Any>({{.*}}) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
// CHECK: return
// This gets emitted down here for some reason
// CHECK-LABEL: sil shared [serializable] [thunk] @_T0So12GenericClassCSQyAByxGGSayxG13arrayOfThings_tcfcTO
// CHECK: objc_method {{%.*}} : $GenericClass<T>, #GenericClass.init!initializer.1.foreign {{.*}}, $@convention(objc_method) @pseudogeneric <τ_0_0 where τ_0_0 : AnyObject> (NSArray, @owned GenericClass<τ_0_0>) -> @owned Optional<GenericClass<τ_0_0>>
// Make sure we emitted the witness table for the above conformance
// CHECK-LABEL: sil_witness_table shared [serialized] GenericOption: Hashable module objc_generics {
// CHECK: method #Hashable.hashValue!getter.1: {{.*}}: @_T0SC13GenericOptionVs8Hashable13objc_genericssACP9hashValueSivgTW
// CHECK: }
| apache-2.0 | c80062a3648fe0a2b67067ca29c423e6 | 57.662069 | 284 | 0.693981 | 3.453512 | false | false | false | false |
ricardorachaus/pingaudio | Pingaudio/Pingaudio/PAExporter.swift | 1 | 2784 | //
// PAExporter.swift
// Pingaudio
//
// Created by Miguel Nery on 01/06/17.
// Copyright © 2017 Rachaus. All rights reserved.
//
import AVFoundation
class PAExporter: PAExporterDelegate {
fileprivate var exportStatus: String
public init() {
exportStatus = ""
}
func export(composition: AVMutableComposition, completion: @escaping (_ output: URL?) -> Void) {
let fileManager = FileManager()
let outputPath = fileManager.temporaryDirectory.appendingPathComponent("\(Date().timeIntervalSince1970).m4a")
guard let exporter = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A) else { return }
exporter.outputURL = outputPath
exporter.outputFileType = AVFileTypeAppleM4A
exporter.shouldOptimizeForNetworkUse = true
exporter.exportAsynchronously() {
self.updateStatus(exporterStatus: exporter.status)
if let error = exporter.error {
print(error.localizedDescription)
completion(nil)
} else {
completion(outputPath)
}
}
}
func export(composition: AVMutableComposition, in time: CMTimeRange, completion: @escaping (_ output: URL?) -> Void) {
let fileManager = FileManager()
let outputPath = fileManager.temporaryDirectory.appendingPathComponent("\(Date().timeIntervalSince1970).m4a")
guard let exporter = AVAssetExportSession(asset: composition, presetName: AVAssetExportPresetAppleM4A) else {
print("wtf")
return
}
exporter.outputURL = outputPath
exporter.outputFileType = AVFileTypeAppleM4A
exporter.shouldOptimizeForNetworkUse = true
exporter.timeRange = time
exporter.exportAsynchronously() {
self.updateStatus(exporterStatus: exporter.status)
if let error = exporter.error {
print(error.localizedDescription)
completion(nil)
} else {
completion(outputPath)
}
}
}
func updateStatus(exporterStatus: AVAssetExportSessionStatus) {
var statusMessage: String!
switch exporterStatus {
case .waiting:
statusMessage = "waiting"
case .exporting:
statusMessage = "exporting"
case .cancelled:
statusMessage = "cancelled"
case .completed:
statusMessage = "completed"
case .failed:
statusMessage = "failed"
case .unknown:
statusMessage = "unknown"
}
exportStatus = statusMessage
print(statusMessage)
}
}
| mit | 09232ba4722a3e2e5f6478b2e6b44ead | 32.53012 | 126 | 0.60654 | 5.577154 | false | false | false | false |
zeroc-ice/ice | swift/test/TestDriver/iOS/ControllerI.swift | 4 | 8513 | //
// Copyright (c) ZeroC, Inc. All rights reserved.
//
import Foundation
import Ice
import TestCommon
class ProcessI: CommonProcess {
var _helper: ControllerHelperI
init(helper: ControllerHelperI) {
_helper = helper
}
func waitReady(timeout: Int32, current _: Ice.Current) throws {
try _helper.waitReady(timeout: timeout)
}
func waitSuccess(timeout: Int32, current _: Ice.Current) throws -> Int32 {
return try _helper.waitSuccess(timeout: timeout)
}
func terminate(current: Ice.Current) throws -> String {
_helper.shutdown()
guard let adapter = current.adapter else {
fatalError()
}
try adapter.remove(current.id)
return _helper.getOutput()
}
}
class ProcessControllerI: CommonProcessController {
var _view: ViewController
var _ipv4: String
var _ipv6: String
var _bundleName: String = ""
//
// Run each process in its own queue
//
var _serverDispatchQueue: DispatchQueue
var _clientDispatchQueue: DispatchQueue
init(view: ViewController, ipv4: String, ipv6: String) {
_view = view
_ipv4 = ipv4
_ipv6 = ipv6
_serverDispatchQueue = DispatchQueue(label: "Server", qos: .userInitiated)
_clientDispatchQueue = DispatchQueue(label: "Client", qos: .userInitiated)
}
func start(testsuite: String,
exe: String,
args: CommonStringSeq,
current: Ice.Current) throws -> CommonProcessPrx? {
guard let adapter = current.adapter else {
throw Ice.RuntimeError("Error")
}
_view.println("starting \(testsuite) \(exe)... ")
//
// For a Client test reuse the Server or ServerAMD bundle
// if it has been loaded.
//
_bundleName = testsuite.split(separator: "/").map {
if let c = $0.first {
return c.uppercased() + $0.dropFirst()
} else {
return String($0)
}
}.joined(separator: "")
if exe == "ServerAMD" {
_bundleName += "AMD"
}
let helper = ControllerHelperI(view: _view,
bundleName: _bundleName,
args: args,
exe: exe,
queue: (exe == "Server" ||
exe == "ServerAMD") ? _serverDispatchQueue : _clientDispatchQueue)
helper.run()
return try uncheckedCast(prx: adapter.addWithUUID(
CommonProcessDisp(ProcessI(helper: helper))), type: CommonProcessPrx.self)
}
func getHost(protocol _: String,
ipv6: Bool,
current _: Ice.Current) throws -> String {
return ipv6 ? _ipv6 : _ipv4
}
}
class ControllerI {
var _communicator: Ice.Communicator!
static var _controller: ControllerI!
init(view: ViewController, ipv4: String, ipv6: String) throws {
let properties = Ice.createProperties()
properties.setProperty(key: "Ice.Plugin.IceDiscovery", value: "1")
properties.setProperty(key: "Ice.ThreadPool.Server.SizeMax", value: "10")
properties.setProperty(key: "IceDiscovery.DomainId", value: "TestController")
properties.setProperty(key: "ControllerAdapter.Endpoints", value: "tcp")
properties.setProperty(key: "ControllerAdapter.AdapterId", value: UUID().uuidString)
// properties.setProperty(key: "Ice.Trace.Protocol", value: "2")
// properties.setProperty(key: "Ice.Trace.Network", value: "3")
var initData = Ice.InitializationData()
initData.properties = properties
_communicator = try Ice.initialize(initData)
let adapter = try _communicator.createObjectAdapter("ControllerAdapter")
var ident = Ice.Identity()
#if targetEnvironment(simulator)
ident.category = "iPhoneSimulator"
#else
ident.category = "iPhoneOS"
#endif
ident.name = "com.zeroc.Swift-Test-Controller"
try adapter.add(servant: CommonProcessControllerDisp(
ProcessControllerI(view: view, ipv4: ipv4, ipv6: ipv6)), id: ident)
try adapter.activate()
}
public func destroy() {
precondition(_communicator != nil)
_communicator.destroy()
}
public class func stopController() {
if _controller != nil {
_controller.destroy()
_controller = nil
}
}
public class func startController(view: ViewController, ipv4: String, ipv6: String) throws {
_controller = try ControllerI(view: view, ipv4: ipv4, ipv6: ipv6)
}
}
class ControllerHelperI: ControllerHelper, TextWriter {
var _view: ViewController
var _args: [String]
var _ready: Bool
var _completed: Bool
var _status: Int32
var _out: String
var _communicator: Ice.Communicator!
var _semaphore: DispatchSemaphore
var _exe: String
var _queue: DispatchQueue
var _bundleName: String
public init(view: ViewController, bundleName: String, args: [String], exe: String, queue: DispatchQueue) {
_view = view
_bundleName = bundleName
_args = args
_ready = false
_completed = false
_status = 1
_out = ""
_communicator = nil
_exe = exe
_semaphore = DispatchSemaphore(value: 0)
_queue = queue
}
public func serverReady() {
_ready = true
_semaphore.signal()
}
public func communicatorInitialized(communicator: Ice.Communicator) {
_communicator = communicator
}
public func loggerPrefix() -> String {
return _bundleName
}
public func write(_ msg: String) {
_out += msg
}
public func writeLine(_ msg: String) {
write("\(msg)\n")
}
public func completed(status: Int32) {
_completed = true
_status = status
_semaphore.signal()
}
public func run() {
let path = "\(Bundle.main.bundlePath)/Frameworks/\(_bundleName).bundle"
guard let bundle = Bundle(url: URL(fileURLWithPath: path)) else {
writeLine("Bundle: `\(path)' not found")
completed(status: 1)
return
}
let className = "\(_bundleName).\(_exe)"
guard let helperClass = bundle.classNamed(className) as? TestHelperI.Type else {
writeLine("test: `\(className)' not found")
completed(status: 1)
return
}
_queue.async {
do {
let testHelper = helperClass.init()
testHelper.setControllerHelper(controllerHelper: self)
testHelper.setWriter(writer: self)
try testHelper.run(args: self._args)
self.completed(status: 0)
} catch {
self.writeLine("Error: \(error)")
self.completed(status: 1)
}
}
}
public func shutdown() {
guard let communicator = _communicator else {
return
}
communicator.shutdown()
}
public func waitReady(timeout: Int32) throws {
var ex: Error?
do {
while !_ready, !_completed {
if _semaphore.wait(timeout: .now() + Double(timeout)) == .timedOut {
throw CommonProcessFailedException(reason: "timed out waiting for the process to be ready")
}
}
if _completed, _status != 0 {
throw CommonProcessFailedException(reason: _out)
}
} catch {
ex = error
}
if let ex = ex {
throw ex
}
}
public func waitSuccess(timeout: Int32) throws -> Int32 {
var ex: Error?
do {
while !_completed {
if _semaphore.wait(timeout: .now() + Double(timeout)) == .timedOut {
throw CommonProcessFailedException(reason: "timed out waiting for the process to succeed")
}
}
if _completed, _status != 0 {
throw CommonProcessFailedException(reason: _out)
}
} catch {
ex = error
}
if let ex = ex {
throw ex
}
return _status
}
public func getOutput() -> String {
return _out
}
}
| gpl-2.0 | 421cabce0f21ea9b8694901d4b5d8e7c | 28.975352 | 111 | 0.560554 | 4.571966 | false | false | false | false |
akupara/Vishnu | Vishnu/Matsya/UIViewController+DLStoryboardExtensionViewController.swift | 1 | 3181 | //
// UIViewController+DLStoryboardExtensionViewController.swift
// DLControl
//
// Created by Daniel Lu on 2/18/16.
// Copyright © 2016 Daniel Lu. All rights reserved.
//
import UIKit
import Vishnu
public extension UIViewController {
public func presentInstantiateViewControllerWithIdentifier(identifier: String, animated: Bool, inStoryboardNamed name:String, withParams params:[String: AnyObject]? = nil, inViewController: UIViewController? = nil) {
presentinstantiateViewControllerWithIdentifier(identifier, animated: animated, inStoryboard: storyboardNamed(name), withParams: params, inViewController: inViewController)
}
public func presentinstantiateViewControllerWithIdentifier(identifier: String, animated: Bool, inStoryboard: UIStoryboard, withParams params:[String:AnyObject]? = nil, inViewController: UIViewController? = nil) {
presentViewController(instantiateViewControllerWithIdentifier(identifier, inStoryboard: inStoryboard), animated: animated, withParams: params, inViewController: inViewController)
}
public func presentViewController(controller:UIViewController, animated: Bool, withParams params:[String: AnyObject]? = nil, inViewController: UIViewController? = nil) {
setupParams(controller, params: params)
let sourceController:UIViewController!
if inViewController != nil {
sourceController = inViewController
} else {
sourceController = self
}
if let navi = sourceController as? UINavigationController {
navi.pushViewController(controller, animated: animated)
} else if let navi = sourceController.navigationController {
navi.pushViewController(controller, animated: animated)
} else {
sourceController.presentViewController(controller, animated: animated, completion: nil)
}
}
internal func storyboardNamed(name:String, bundle: NSBundle? = nil) -> UIStoryboard {
return UIStoryboard(name: name, bundle: bundle)
}
internal func instantiateViewControllerWithIdentifier(identifier:String, inStoryboard: UIStoryboard) -> UIViewController {
return inStoryboard.instantiateViewControllerWithIdentifier(identifier)
}
internal func instantiateViewControllerWithIdentifier(identifier:String, inStoryboardNamed name: String, bundle:NSBundle? = nil) -> UIViewController {
return instantiateViewControllerWithIdentifier(identifier, inStoryboard: storyboardNamed(name, bundle: bundle))
}
internal func instantiateInitialViewControllerInStoryboardNamed(name:String, bundle:NSBundle? = nil) -> UIViewController? {
return storyboardNamed(name, bundle: bundle).instantiateInitialViewController()
}
internal func setupParams(target:UIViewController, params:[String:AnyObject]?) {
if params != nil {
for (name, value) in params! {
let method = "set\(name.upperCaseFirst()):"
if target.respondsToSelector(Selector(method)) {
target.setValue(value, forKey: name)
}
}
}
}
} | mit | 84e1194ea7e557773c0458c52f7d2420 | 47.19697 | 220 | 0.715723 | 5.658363 | false | false | false | false |
therealbnut/swift | stdlib/public/core/BridgeObjectiveC.swift | 1 | 21076 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if _runtime(_ObjC)
/// 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 element of the source container.
public protocol _ObjectiveCBridgeable {
associatedtype _ObjectiveCType : AnyObject
/// 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<Element>`, we can defer
/// the checking for the individual elements of the array.
///
/// - parameter result: The location where the result is written. The optional
/// will always contain a value.
static func _forceBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout 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.
///
/// - parameter 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.
@discardableResult
static func _conditionallyBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout Self?
) -> Bool
/// Bridge from an Objective-C object of the bridged class type to a
/// value of the Self type.
///
/// This bridging operation is used for unconditional bridging when
/// interoperating with Objective-C code, either in the body of an
/// Objective-C thunk or when calling Objective-C code, and may
/// defer complete checking until later. For example, when bridging
/// from `NSArray` to `Array<Element>`, we can defer the checking
/// for the individual elements of the array.
///
/// \param source The Objective-C object from which we are
/// bridging. This optional value will only be `nil` in cases where
/// an Objective-C method has returned a `nil` despite being marked
/// as `_Nonnull`/`nonnull`. In most such cases, bridging will
/// generally force the value immediately. However, this gives
/// bridging the flexibility to substitute a default value to cope
/// with historical decisions, e.g., an existing Objective-C method
/// that returns `nil` to for "empty result" rather than (say) an
/// empty array. In such cases, when `nil` does occur, the
/// implementation of `Swift.Array`'s conformance to
/// `_ObjectiveCBridgeable` will produce an empty array rather than
/// dynamically failing.
static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> Self
}
//===--- Bridging for metatypes -------------------------------------------===//
/// A stand-in for a value of metatype type.
///
/// The language and runtime do not yet support protocol conformances for
/// structural types like metatypes. However, we can use a struct that contains
/// a metatype, make it conform to _ObjectiveCBridgeable, and its witness table
/// will be ABI-compatible with one that directly provided conformance to the
/// metatype type itself.
@_fixed_layout
public struct _BridgeableMetatype: _ObjectiveCBridgeable {
internal var value: AnyObject.Type
public typealias _ObjectiveCType = AnyObject
public func _bridgeToObjectiveC() -> AnyObject {
return value
}
public static func _forceBridgeFromObjectiveC(
_ source: AnyObject,
result: inout _BridgeableMetatype?
) {
result = _BridgeableMetatype(value: source as! AnyObject.Type)
}
public static func _conditionallyBridgeFromObjectiveC(
_ source: AnyObject,
result: inout _BridgeableMetatype?
) -> Bool {
if let type = source as? AnyObject.Type {
result = _BridgeableMetatype(value: type)
return true
}
result = nil
return false
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?)
-> _BridgeableMetatype {
var result: _BridgeableMetatype?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
//===--- Bridging facilities written in Objective-C -----------------------===//
// Functions that must discover and possibly use an arbitrary type's
// conformance to a given protocol. See ../runtime/Metadata.cpp for
// implementations.
//===----------------------------------------------------------------------===//
/// Bridge an arbitrary value to an Objective-C object.
///
/// - If `T` is a class type, it is always bridged verbatim, the function
/// returns `x`;
///
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`,
/// returns the result of `x._bridgeToObjectiveC()`;
///
/// - otherwise, we use **boxing** to bring the value into Objective-C.
/// The value is wrapped in an instance of a private Objective-C class
/// that is `id`-compatible and dynamically castable back to the type of
/// the boxed value, but is otherwise opaque.
///
/// COMPILER_INTRINSIC
public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return unsafeBitCast(x, to: AnyObject.self)
}
return _bridgeAnythingNonVerbatimToObjectiveC(x)
}
/// COMPILER_INTRINSIC
@_silgen_name("_swift_bridgeAnythingNonVerbatimToObjectiveC")
public func _bridgeAnythingNonVerbatimToObjectiveC<T>(_ x: T) -> AnyObject
/// Convert a purportedly-nonnull `id` value from Objective-C into an Any.
///
/// Since Objective-C APIs sometimes get their nullability annotations wrong,
/// this includes a failsafe against nil `AnyObject`s, wrapping them up as
/// a nil `AnyObject?`-inside-an-`Any`.
///
/// COMPILER_INTRINSIC
public func _bridgeAnyObjectToAny(_ possiblyNullObject: AnyObject?) -> Any {
if let nonnullObject = possiblyNullObject {
return nonnullObject // AnyObject-in-Any
}
return possiblyNullObject as Any
}
/// Convert `x` from its Objective-C representation to its Swift
/// representation.
///
/// - If `T` is a class type:
/// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged
/// verbatim, the function returns `x`;
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`:
/// + if the dynamic type of `x` is not `T._ObjectiveCType`
/// or a subclass of it, trap;
/// + otherwise, returns the result of `T._forceBridgeFromObjectiveC(x)`;
/// - otherwise, trap.
public func _forceBridgeFromObjectiveC<T>(_ x: AnyObject, _: T.Type) -> T {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return x as! T
}
var result: T?
_bridgeNonVerbatimFromObjectiveC(x, T.self, &result)
return result!
}
/// Convert `x` from its Objective-C representation to its Swift
/// representation.
@_silgen_name("_forceBridgeFromObjectiveC_bridgeable")
public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> (
_ x: T._ObjectiveCType,
_: T.Type
) -> T {
var result: T?
T._forceBridgeFromObjectiveC(x, result: &result)
return result!
}
/// Attempt to convert `x` from its Objective-C representation to its Swift
/// representation.
///
/// - If `T` is a class type:
/// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged
/// verbatim, the function returns `x`;
/// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`:
/// + otherwise, if the dynamic type of `x` is not `T._ObjectiveCType`
/// or a subclass of it, the result is empty;
/// + otherwise, returns the result of
/// `T._conditionallyBridgeFromObjectiveC(x)`;
/// - otherwise, the result is empty.
public func _conditionallyBridgeFromObjectiveC<T>(
_ x: AnyObject,
_: T.Type
) -> T? {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return x as? T
}
var result: T?
_ = _bridgeNonVerbatimFromObjectiveCConditional(x, T.self, &result)
return result
}
/// Attempt to convert `x` from its Objective-C representation to its Swift
/// representation.
@_silgen_name("_conditionallyBridgeFromObjectiveC_bridgeable")
public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>(
_ x: T._ObjectiveCType,
_: T.Type
) -> T? {
var result: T?
T._conditionallyBridgeFromObjectiveC (x, result: &result)
return result
}
@_silgen_name("_swift_bridgeNonVerbatimFromObjectiveC")
func _bridgeNonVerbatimFromObjectiveC<T>(
_ x: AnyObject,
_ nativeType: T.Type,
_ result: inout T?
)
/// Helper stub to upcast to Any and store the result to an inout Any?
/// on the C++ runtime's behalf.
// COMPILER_INTRINSIC
@_silgen_name("_swift_bridgeNonVerbatimFromObjectiveCToAny")
public func _bridgeNonVerbatimFromObjectiveCToAny(
_ x: AnyObject,
_ result: inout Any?
) {
result = x as Any
}
/// Helper stub to upcast to Optional on the C++ runtime's behalf.
// COMPILER_INTRINSIC
@_silgen_name("_swift_bridgeNonVerbatimBoxedValue")
public func _bridgeNonVerbatimBoxedValue<NativeType>(
_ x: UnsafePointer<NativeType>,
_ result: inout NativeType?
) {
result = x.pointee
}
/// Runtime optional to conditionally perform a bridge from an object to a value
/// type.
///
/// - parameter result: Will be set to the resulting value if bridging succeeds, and
/// unchanged otherwise.
///
/// - Returns: `true` to indicate success, `false` to indicate failure.
@_silgen_name("_swift_bridgeNonVerbatimFromObjectiveCConditional")
func _bridgeNonVerbatimFromObjectiveCConditional<T>(
_ x: AnyObject,
_ nativeType: T.Type,
_ result: inout T?
) -> Bool
/// Determines if values of a given type can be converted to an Objective-C
/// representation.
///
/// - If `T` is a class type, returns `true`;
/// - otherwise, returns whether `T` conforms to `_ObjectiveCBridgeable`.
public func _isBridgedToObjectiveC<T>(_: T.Type) -> Bool {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return true
}
return _isBridgedNonVerbatimToObjectiveC(T.self)
}
@_silgen_name("_swift_isBridgedNonVerbatimToObjectiveC")
func _isBridgedNonVerbatimToObjectiveC<T>(_: T.Type) -> Bool
/// A type that's bridged "verbatim" does not conform to
/// `_ObjectiveCBridgeable`, and can have its bits reinterpreted as an
/// `AnyObject`. When this function returns true, the storage of an
/// `Array<T>` can be `unsafeBitCast` as an array of `AnyObject`.
public func _isBridgedVerbatimToObjectiveC<T>(_: T.Type) -> Bool {
return _isClassOrObjCExistential(T.self)
}
/// Retrieve the Objective-C type to which the given type is bridged.
public func _getBridgedObjectiveCType<T>(_: T.Type) -> Any.Type? {
if _fastPath(_isClassOrObjCExistential(T.self)) {
return T.self
}
return _getBridgedNonVerbatimObjectiveCType(T.self)
}
@_silgen_name("_swift_getBridgedNonVerbatimObjectiveCType")
func _getBridgedNonVerbatimObjectiveCType<T>(_: T.Type) -> Any.Type?
// -- Pointer argument bridging
@_transparent
internal var _nilNativeObject: AnyObject? {
return nil
}
/// 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<Pointee>`, which is passed as-is.
///
/// Passing pointers to mutable arrays of ObjC class pointers is not
/// directly supported. Unlike `UnsafeMutablePointer<Pointee>`,
/// `AutoreleasingUnsafeMutablePointer<Pointee>` 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.
@_fixed_layout
public struct AutoreleasingUnsafeMutablePointer<Pointee /* TODO : class */>
: Equatable, _Pointer {
public let _rawValue: Builtin.RawPointer
@_transparent
public // COMPILER_INTRINSIC
init(_ _rawValue: Builtin.RawPointer) {
self._rawValue = _rawValue
}
/// Access the `Pointee` instance referenced by `self`.
///
/// - Precondition: the pointee has been initialized with an instance of type
/// `Pointee`.
public var pointee: Pointee {
/// Retrieve the value the pointer points to.
@_transparent get {
// We can do a strong load normally.
return unsafeBitCast(self, to: UnsafeMutablePointer<Pointee>.self).pointee
}
/// Set the value the pointer points to, copying over the previous value.
///
/// AutoreleasingUnsafeMutablePointers are assumed to reference a
/// value with __autoreleasing ownership semantics, like 'NSFoo**'
/// in ARC. This autoreleases the argument before trivially
/// storing it to the referenced memory.
@_transparent nonmutating set {
// Autorelease the object reference.
typealias OptionalAnyObject = AnyObject?
let newAnyObject = unsafeBitCast(newValue, to: OptionalAnyObject.self)
Builtin.retain(newAnyObject)
Builtin.autorelease(newAnyObject)
// Trivially assign it as an OpaquePointer; the pointer references an
// autoreleasing slot, so retains/releases of the original value are
// unneeded.
typealias OptionalUnmanaged = Unmanaged<AnyObject>?
UnsafeMutablePointer<Pointee>(_rawValue).withMemoryRebound(
to: OptionalUnmanaged.self, capacity: 1) {
if let newAnyObject = newAnyObject {
$0.pointee = Unmanaged.passUnretained(newAnyObject)
}
else {
$0.pointee = nil
}
}
}
}
/// Access the `i`th element of the raw array pointed to by
/// `self`.
///
/// - Precondition: `self != nil`.
public subscript(i: Int) -> Pointee {
@_transparent
get {
// We can do a strong load normally.
return (UnsafePointer<Pointee>(self) + i).pointee
}
}
/// Explicit construction from an UnsafeMutablePointer.
///
/// This is inherently unsafe; UnsafeMutablePointer assumes the
/// referenced memory has +1 strong ownership semantics, whereas
/// AutoreleasingUnsafeMutablePointer implies +0 semantics.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@_transparent public
init<U>(_ from: UnsafeMutablePointer<U>) {
self._rawValue = from._rawValue
}
/// Explicit construction from an UnsafeMutablePointer.
///
/// Returns nil if `from` is nil.
///
/// This is inherently unsafe; UnsafeMutablePointer assumes the
/// referenced memory has +1 strong ownership semantics, whereas
/// AutoreleasingUnsafeMutablePointer implies +0 semantics.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@_transparent public
init?<U>(_ from: UnsafeMutablePointer<U>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
/// Explicit construction from a UnsafePointer.
///
/// This is inherently unsafe because UnsafePointers do not imply
/// mutability.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@_transparent
init<U>(_ from: UnsafePointer<U>) {
self._rawValue = from._rawValue
}
/// Explicit construction from a UnsafePointer.
///
/// Returns nil if `from` is nil.
///
/// This is inherently unsafe because UnsafePointers do not imply
/// mutability.
///
/// - Warning: Accessing `pointee` as a type that is unrelated to
/// the underlying memory's bound type is undefined.
@_transparent
init?<U>(_ from: UnsafePointer<U>?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
}
extension UnsafeMutableRawPointer {
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert.
@_transparent
public init<T>(_ other: AutoreleasingUnsafeMutablePointer<T>) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(_ other: AutoreleasingUnsafeMutablePointer<T>?) {
guard let unwrapped = other else { return nil }
self.init(unwrapped)
}
}
extension UnsafeRawPointer {
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert.
@_transparent
public init<T>(_ other: AutoreleasingUnsafeMutablePointer<T>) {
_rawValue = other._rawValue
}
/// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer`
/// instance.
///
/// - Parameter other: The pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(_ other: AutoreleasingUnsafeMutablePointer<T>?) {
guard let unwrapped = other else { return nil }
self.init(unwrapped)
}
}
extension AutoreleasingUnsafeMutablePointer : CustomDebugStringConvertible {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
return _rawPointerToString(_rawValue)
}
}
@_transparent
public func == <Pointee>(
lhs: AutoreleasingUnsafeMutablePointer<Pointee>,
rhs: AutoreleasingUnsafeMutablePointer<Pointee>
) -> Bool {
return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue))
}
@_fixed_layout
internal struct _CocoaFastEnumerationStackBuf {
// Clang uses 16 pointers. So do we.
internal var _item0: UnsafeRawPointer?
internal var _item1: UnsafeRawPointer?
internal var _item2: UnsafeRawPointer?
internal var _item3: UnsafeRawPointer?
internal var _item4: UnsafeRawPointer?
internal var _item5: UnsafeRawPointer?
internal var _item6: UnsafeRawPointer?
internal var _item7: UnsafeRawPointer?
internal var _item8: UnsafeRawPointer?
internal var _item9: UnsafeRawPointer?
internal var _item10: UnsafeRawPointer?
internal var _item11: UnsafeRawPointer?
internal var _item12: UnsafeRawPointer?
internal var _item13: UnsafeRawPointer?
internal var _item14: UnsafeRawPointer?
internal var _item15: UnsafeRawPointer?
@_transparent
internal var count: Int {
return 16
}
internal init() {
_item0 = nil
_item1 = _item0
_item2 = _item0
_item3 = _item0
_item4 = _item0
_item5 = _item0
_item6 = _item0
_item7 = _item0
_item8 = _item0
_item9 = _item0
_item10 = _item0
_item11 = _item0
_item12 = _item0
_item13 = _item0
_item14 = _item0
_item15 = _item0
_sanityCheck(MemoryLayout.size(ofValue: self) >=
MemoryLayout<Optional<UnsafeRawPointer>>.size * count)
}
}
extension AutoreleasingUnsafeMutablePointer {
@available(*, unavailable, renamed: "Pointee")
public typealias Memory = Pointee
@available(*, unavailable, renamed: "pointee")
public var memory: Pointee {
Builtin.unreachable()
}
@available(*, unavailable, message: "Removed in Swift 3. Please use nil literal instead.")
public init() {
Builtin.unreachable()
}
}
/// Get the ObjC type encoding for a type as a pointer to a C string.
///
/// This is used by the Foundation overlays. The compiler will error if the
/// passed-in type is generic or not representable in Objective-C
@_transparent
public func _getObjCTypeEncoding<T>(_ type: T.Type) -> UnsafePointer<Int8> {
// This must be `@_transparent` because `Builtin.getObjCTypeEncoding` is
// only supported by the compiler for concrete types that are representable
// in ObjC.
return UnsafePointer(Builtin.getObjCTypeEncoding(type))
}
#endif
| apache-2.0 | 88319fde7f9dc63758275f7f9a5a72fe | 33.836364 | 92 | 0.694819 | 4.390833 | false | false | false | false |
ntwf/TheTaleClient | TheTale/Stores/Login/Login.swift | 1 | 756 | //
// Login.swift
// the-tale
//
// Created by Mikhail Vospennikov on 21/05/2017.
// Copyright © 2017 Mikhail Vospennikov. All rights reserved.
//
import Foundation
struct Login {
var accountID: Int
var accountName: String
var sessionExpireAt: Double
}
extension Login: JSONDecodable {
init?(jsonObject: JSON) {
guard let accountID = jsonObject["account_id"] as? Int,
let accountName = jsonObject["account_name"] as? String,
let sessionExpireAt = jsonObject["session_expire_at"] as? Double else {
return nil
}
self.accountID = accountID
self.accountName = accountName
self.sessionExpireAt = sessionExpireAt
}
init?() {
self.init(jsonObject: [:])
}
}
| mit | 1759dded6b29b3f1010c35c3a4a60d50 | 20.571429 | 81 | 0.642384 | 4.05914 | false | false | false | false |
lanjing99/iOSByTutorials | iOS 9 by tutorials/05-multitasking/starter/Travelog/TravelogKit/LogCollection.swift | 1 | 1910 | /*
* Copyright (c) 2015 Razeware LLC
*
* 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 LogCollection {
// MARK: Private
private var logs = [NSDate: BaseLog]()
func dictionaryRepresentation() -> Dictionary <NSDate, NSCoding> {
return logs
}
// MARK: Public
public init() {}
/// Adds a BaseLog or any of its subclasses to the collection.
public func addLog(log: BaseLog) {
logs[log.date] = log
}
/// Removes a BaseLog or any of its subclasses from the collection.
public func removeLog(log: BaseLog) {
logs[log.date] = nil
}
/// Returns an array of BaseLog or any of its subclasses sorted by date of creation.
public func sortedLogs(ordered: NSComparisonResult) -> [BaseLog] {
let allLogs = logs.values
let sorted = allLogs.sort { return $0.date.compare($1.date) == ordered }
return sorted
}
} | mit | 716a8b4b0ab12c86dc6eabc537fb3017 | 33.125 | 86 | 0.726178 | 4.292135 | false | false | false | false |
MenloHacks/ios-app | Menlo Hacks/Menlo Hacks/MEHMentorshipPageViewController.swift | 1 | 3384 | //
// MEHMentorshipPageViewController.swift
// Menlo Hacks
//
// Created by Jason Scharff on 3/5/17.
// Copyright © 2017 MenloHacks. All rights reserved.
//
import Foundation
import UIKit
import Parchment
import Bolts
@objc class MEHMentorshipPageViewController: UIViewController {
var pageMenu : FixedPagingViewController!
override func viewWillAppear(_ animated: Bool) {
if (self.parent?.navigationItem.rightBarButtonItem == nil) {
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTicket(sender:)))
self.parent?.navigationItem.rightBarButtonItem = addButton;
}
}
override func viewDidLoad(){
let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(addTicket(sender:)))
self.parent?.navigationItem.rightBarButtonItem = addButton;
let vc1 = MEHMentorshipViewController()
vc1.predicates = [NSPredicate(format:"rawStatus = %i", MEHMentorTicketStatusOpen.rawValue)]
vc1.fetchFromServer = { () -> BFTask<AnyObject> in
return MEHMentorshipStoreController.shared().fetchQueue()
}
vc1.title = "Queue";
let vc2 = MEHMentorshipViewController()
vc2.requiresLogin = true
vc2.predicates = [NSPredicate(format: "claimedByMe = 1 AND rawStatus = %i", MEHMentorTicketStatusClaimed.rawValue)]
vc2.fetchFromServer = { () -> BFTask<AnyObject> in
return MEHMentorshipStoreController.shared().fetchClaimedQueue()
}
vc2.title = "Claimed";
let vc3 = MEHMentorshipViewController()
vc3.requiresLogin = true
vc3.predicates = [NSPredicate(format: "isMine = 1 AND rawStatus = %i", MEHMentorTicketStatusOpen.rawValue),
NSPredicate(format: "isMine = 1 AND rawStatus = %i", MEHMentorTicketStatusClaimed.rawValue),
NSPredicate(format: "isMine = 1 AND rawStatus = %i", MEHMentorTicketStatusExpired.rawValue),
NSPredicate(format: "isMine = 1 AND rawStatus = %i", MEHMentorTicketStatusClosed.rawValue)];
vc3.predicateLabels = ["Open", "In-Progress", "Expired", "Closed"]
vc3.fetchFromServer = { () -> BFTask<AnyObject> in
return MEHMentorshipStoreController.shared().fetchUserQueue()
}
vc3.title = "My Tickets";
let controllers = [vc1, vc2, vc3]
pageMenu = FixedPagingViewController(viewControllers: controllers)
pageMenu.textColor = UIColor.menloHacksGray()
pageMenu.font = UIFont(name: "Avenir", size: 16.0)!
pageMenu.selectedTextColor = UIColor.menloHacksPurple()
pageMenu.indicatorColor = UIColor.menloHacksPurple()
pageMenu.menuBackgroundColor = UIColor(red: 247.0/255.0, green: 247.0/255.0, blue: 247.0/255.0, alpha: 1.0)
pageMenu.menuItemSize = .sizeToFit(minWidth: 125, height: 40)
AutolayoutHelper.configureView(self.view, fillWithSubView: pageMenu.view)
}
@objc func addTicket(sender : AnyObject) {
let vc = MEHAddMentorTicketViewController()
self.displayContentController(vc)
}
}
| mit | 08b65f2393c4a1911b93faca1905e006 | 36.588889 | 123 | 0.632575 | 4.387808 | false | false | false | false |
ahoppen/swift | test/Constraints/patterns.swift | 4 | 13203 | // RUN: %target-typecheck-verify-swift
// Leaf expression patterns are matched to corresponding pieces of a switch
// subject (TODO: or ~= expression) using ~= overload resolution.
switch (1, 2.5, "three") {
case (1, _, _):
()
// Double is ExpressibleByIntegerLiteral
case (_, 2, _),
(_, 2.5, _),
(_, _, "three"):
()
// ~= overloaded for (Range<Int>, Int)
case (0..<10, _, _),
(0..<10, 2.5, "three"),
(0...9, _, _),
(0...9, 2.5, "three"):
()
default:
()
}
switch (1, 2) {
case (var a, a): // expected-error {{cannot find 'a' in scope}}
()
}
// 'is' patterns can perform the same checks that 'is' expressions do.
protocol P { func p() }
class B : P {
init() {}
func p() {}
func b() {}
}
class D : B {
override init() { super.init() }
func d() {}
}
class E {
init() {}
func e() {}
}
struct S : P {
func p() {}
func s() {}
}
// Existential-to-concrete.
var bp : P = B()
switch bp {
case is B,
is D,
is S:
()
case is E:
()
default:
()
}
switch bp {
case let b as B:
b.b()
case let d as D:
d.b()
d.d()
case let s as S:
s.s()
case let e as E:
e.e()
default:
()
}
// Super-to-subclass.
var db : B = D()
switch db {
case is D:
()
case is E: // expected-warning {{always fails}}
()
default:
()
}
// Raise an error if pattern productions are used in expressions.
var b = var x // expected-error{{expected initial value after '='}} expected-error {{type annotation missing in pattern}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}}
var c = is Int // expected-error{{expected initial value after '='}} expected-error {{expected expression}} expected-error {{consecutive statements on a line must be separated by ';'}} {{8-8=;}}
// TODO: Bad recovery in these cases. Although patterns are never valid
// expr-unary productions, it would be good to parse them anyway for recovery.
//var e = 2 + var y
//var e = var y + 2
// 'E.Case' can be used in a dynamic type context as an equivalent to
// '.Case as E'.
protocol HairType {}
enum MacbookHair: HairType {
case HairSupply(S)
}
enum iPadHair<T>: HairType {
case HairForceOne
}
enum Watch {
case Sport, Watch, Edition
}
let hair: HairType = MacbookHair.HairSupply(S())
switch hair {
case MacbookHair.HairSupply(let s):
s.s()
case iPadHair<S>.HairForceOne:
()
case iPadHair<E>.HairForceOne:
()
case iPadHair.HairForceOne: // expected-error{{generic enum type 'iPadHair' is ambiguous without explicit generic parameters when matching value of type 'any HairType'}}
()
case Watch.Edition: // expected-warning {{cast from 'any HairType' to unrelated type 'Watch' always fails}}
()
case .HairForceOne: // expected-error{{type 'any HairType' has no member 'HairForceOne'}}
()
default:
break
}
// <rdar://problem/19382878> Introduce new x? pattern
switch Optional(42) {
case let x?: break // expected-warning{{immutable value 'x' was never used; consider replacing with '_' or removing it}} {{10-11=_}}
case nil: break
}
func SR2066(x: Int?) {
// nil literals should still work when wrapped in parentheses
switch x {
case (nil): break
case _?: break
}
switch x {
case ((nil)): break
case _?: break
}
switch (x, x) {
case ((nil), _): break
case (_?, _): break
}
}
// Test x???? patterns.
switch (nil as Int???) {
case let x???: print(x, terminator: "")
case let x??: print(x as Any, terminator: "")
case let x?: print(x as Any, terminator: "")
case 4???: break
case nil??: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
case nil?: break // expected-warning {{case is already handled by previous patterns; consider removing it}}
default: break
}
switch ("foo" as String?) {
case "what": break
default: break
}
// Test some value patterns.
let x : Int?
extension Int {
func method() -> Int { return 42 }
}
func ~= <T : Equatable>(lhs: T?, rhs: T?) -> Bool {
return lhs == rhs
}
switch 4 as Int? {
case x?.method(): break // match value
default: break
}
switch 4 {
case x ?? 42: break // match value
default: break
}
for (var x) in 0...100 {} // expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}}
for var x in 0...100 {} // rdar://20167543 expected-warning{{variable 'x' was never used; consider replacing with '_' or removing it}}
for (let x) in 0...100 { _ = x} // expected-error {{'let' pattern cannot appear nested in an already immutable context}}
var (let y) = 42 // expected-error {{'let' cannot appear nested inside another 'var' or 'let' pattern}}
let (var z) = 42 // expected-error {{'var' cannot appear nested inside another 'var' or 'let' pattern}}
// Crash when re-typechecking EnumElementPattern.
// FIXME: This should actually type-check -- the diagnostics are bogus. But
// at least we don't crash anymore.
protocol PP {
associatedtype E
}
struct A<T> : PP {
typealias E = T
}
extension PP {
func map<T>(_ f: (Self.E) -> T) -> T {}
}
enum EE {
case A
case B
}
func good(_ a: A<EE>) -> Int {
return a.map {
switch $0 {
case .A:
return 1
default:
return 2
}
}
}
func bad(_ a: A<EE>) {
let _ = a.map {
let _: EE = $0
return 1
}
}
func ugly(_ a: A<EE>) {
let _ = a.map {
switch $0 {
case .A:
return 1
default:
return 2
}
}
}
// SR-2057
enum SR2057 {
case foo
}
let sr2057: SR2057?
if case .foo = sr2057 { } // Ok
// Invalid 'is' pattern
class SomeClass {}
if case let doesNotExist as SomeClass:AlsoDoesNotExist {}
// expected-error@-1 {{cannot find type 'AlsoDoesNotExist' in scope}}
// expected-error@-2 {{variable binding in a condition requires an initializer}}
// `.foo` and `.bar(...)` pattern syntax should also be able to match
// static members as expr patterns
struct StaticMembers: Equatable {
init() {}
init(_: Int) {}
init?(opt: Int) {}
static var prop = StaticMembers()
static var optProp: Optional = StaticMembers()
static func method(_: Int) -> StaticMembers { return prop }
static func method(withLabel: Int) -> StaticMembers { return prop }
static func optMethod(_: Int) -> StaticMembers? { return optProp }
static func ==(x: StaticMembers, y: StaticMembers) -> Bool { return true }
}
let staticMembers = StaticMembers()
let optStaticMembers: Optional = StaticMembers()
switch staticMembers {
case .init: break // expected-error{{member 'init(opt:)' expects argument of type 'Int'}}
case .init(opt:): break // expected-error{{member 'init(opt:)' expects argument of type 'Int'}}
case .init(): break
case .init(0): break
case .init(_): break // expected-error{{'_' can only appear in a pattern}}
case .init(let x): break // expected-error{{cannot appear in an expression}}
case .init(opt: 0): break // expected-error{{value of optional type 'StaticMembers?' must be unwrapped to a value of type 'StaticMembers'}}
// expected-note@-1 {{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
// expected-note@-2 {{coalesce using '??' to provide a default when the optional value contains 'nil'}}
case .prop: break
case .optProp: break
case .method: break // expected-error{{member 'method' expects argument of type 'Int'}}
case .method(0): break
case .method(_): break // expected-error{{'_' can only appear in a pattern}}
case .method(let x): break // expected-error{{cannot appear in an expression}}
case .method(withLabel:): break // expected-error{{member 'method(withLabel:)' expects argument of type 'Int'}}
case .method(withLabel: 0): break
case .method(withLabel: _): break // expected-error{{'_' can only appear in a pattern}}
case .method(withLabel: let x): break // expected-error{{cannot appear in an expression}}
case .optMethod: break // expected-error{{member 'optMethod' expects argument of type 'Int'}}
case .optMethod(0): break
}
_ = 0
// rdar://problem/32241441 - Add fix-it for cases in switch with optional chaining
struct S_32241441 {
enum E_32241441 {
case foo
case bar
}
var type: E_32241441 = E_32241441.foo
}
func rdar32241441() {
let s: S_32241441? = S_32241441()
switch s?.type { // expected-error {{switch must be exhaustive}} expected-note {{add missing case: '.none'}}
case .foo: // Ok
break;
case .bar: // Ok
break;
}
}
// SR-6100
struct One<Two> { // expected-note{{'Two' declared as parameter to type 'One'}}
public enum E: Error {
// if you remove associated value, everything works
case SomeError(String)
}
}
func testOne() {
do {
} catch let error { // expected-warning{{'catch' block is unreachable because no errors are thrown in 'do' block}}
if case One.E.SomeError = error {} // expected-error{{generic parameter 'Two' could not be inferred}}
}
}
// SR-8347
// constrain initializer expressions of optional some pattern bindings to be optional
func test8347() -> String {
struct C {
subscript (s: String) -> String? {
return ""
}
subscript (s: String) -> [String] {
return [""]
}
func f() -> String? {
return ""
}
func f() -> Int {
return 3
}
func g() -> String {
return ""
}
func h() -> String {
return ""
}
func h() -> Double {
return 3.0
}
func h() -> Int? { //expected-note{{found this candidate}}
return 2
}
func h() -> Float? { //expected-note{{found this candidate}}
return nil
}
}
let c = C()
if let s = c[""] {
return s
}
if let s = c.f() {
return s
}
if let s = c.g() { //expected-error{{initializer for conditional binding must have Optional type, not 'String'}}
return s
}
if let s = c.h() { //expected-error{{ambiguous use of 'h()'}}
return s
}
}
enum SR_7799 {
case baz
case bar
}
let sr7799: SR_7799? = .bar
switch sr7799 {
case .bar?: break // Ok
case .baz: break // Ok
default: break
}
let sr7799_1: SR_7799?? = .baz
switch sr7799_1 {
case .bar?: break // Ok
case .baz: break // Ok
default: break
}
if case .baz = sr7799_1 {} // Ok
if case .bar? = sr7799_1 {} // Ok
// rdar://problem/60048356 - `if case` fails when `_` pattern doesn't have a label
func rdar_60048356() {
typealias Info = (code: ErrorCode, reason: String)
enum ErrorCode {
case normalClosure
}
enum Failure {
case closed(Info) // expected-note {{'closed' declared here}}
}
enum Reason {
case close(Failure)
}
func test(_ reason: Reason) {
if case .close(.closed((code: .normalClosure, _))) = reason { // Ok
}
}
// rdar://problem/60061646
func test(e: Failure) {
if case .closed(code: .normalClosure, _) = e { // Ok
// expected-warning@-1 {{enum case 'closed' has one associated value that is a tuple of 2 elements}}
}
}
enum E {
case foo((x: Int, y: Int)) // expected-note {{declared here}}
case bar(x: Int, y: Int) // expected-note {{declared here}}
}
func test_destructing(e: E) {
if case .foo(let x, let y) = e { // Ok (destructring)
// expected-warning@-1 {{enum case 'foo' has one associated value that is a tuple of 2 elements}}
_ = x == y
}
if case .bar(let tuple) = e { // Ok (matching via tuple)
// expected-warning@-1 {{enum case 'bar' has 2 associated values; matching them as a tuple is deprecated}}
_ = tuple.0 == tuple.1
}
}
}
// rdar://problem/63510989 - valid pattern doesn't type-check
func rdar63510989() {
enum Value : P {
func p() {}
}
enum E {
case single(P?)
case double(P??)
case triple(P???)
}
func test(e: E) {
if case .single(_ as Value) = e {} // Ok
if case .single(let v as Value) = e {} // Ok
// expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}}
if case .double(_ as Value) = e {} // Ok
if case .double(let v as Value) = e {} // Ok
// expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}}
if case .double(let v as Value?) = e {} // Ok
// expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}}
if case .triple(_ as Value) = e {} // Ok
if case .triple(let v as Value) = e {} // Ok
// expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}}
if case .triple(let v as Value?) = e {} // Ok
// expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}}
if case .triple(let v as Value??) = e {} // Ok
// expected-warning@-1 {{immutable value 'v' was never used; consider replacing with '_' or removing it}}
}
}
// rdar://problem/64157451 - compiler crash when using undefined type in pattern
func rdar64157451() {
enum E {
case foo(Int)
}
func test(e: E) {
if case .foo(let v as DoeNotExist) = e {} // expected-error {{cannot find type 'DoeNotExist' in scope}}
}
}
// rdar://80797176 - circular reference incorrectly diagnosed while reaching for a type of a pattern.
func rdar80797176 () {
for x: Int in [1, 2] where x.bitWidth == 32 { // Ok
}
}
| apache-2.0 | c098da23754942031aa1dfa7884e0709 | 24.293103 | 208 | 0.625615 | 3.535886 | false | false | false | false |
cgoldsby/TvOSMoreButton | Source/Public/Views/TvOSMoreButton.swift | 1 | 10226 | //
// TvOSMoreButton.swift
//
// Copyright (c) 2016-2019 Chris Goldsby
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import UIKit
@objc
open class TvOSMoreButton: UIView {
/*
* FocusableMode.Auto
* Focus is allowed only when the text does not fit on the label.
*/
public enum FocusableMode: Equatable {
case auto
case manual(_ isFocusable: Bool)
}
private lazy var contentView: UIView = {
let contentView = UIView(frame: bounds)
return contentView
}()
private var label: UILabel!
private var focusedView: UIView!
private var selectGestureRecognizer: UIGestureRecognizer!
private var isFocusable = false {
didSet {
if isFocusable {
accessibilityTraits.remove(.notEnabled)
}
else {
accessibilityTraits.insert(.notEnabled)
}
}
}
open var focusableMode: FocusableMode = .auto {
didSet {
switch focusableMode {
case .manual(let isFocusable):
self.isFocusable = isFocusable
case .auto:
updateUI()
}
}
}
@objc open var text: String? {
didSet { updateUI() }
}
@objc open var textColor = UIColor.white {
didSet {
label.textColor = textColor
updateUI()
}
}
@objc open var font = UIFont.systemFont(ofSize: 25) {
didSet {
label.font = font
updateUI()
}
}
@objc open var textAlignment = NSTextAlignment.natural {
didSet { label.textAlignment = textAlignment }
}
@objc open var ellipsesString = String.TvOSMoreButton.ellipses.🌍 {
didSet { updateUI() }
}
@objc open var trailingText = String.TvOSMoreButton.more.🌍 {
didSet { updateUI() }
}
@objc open var trailingTextColor = UIColor.black.withAlphaComponent(0.5) {
didSet { updateUI() }
}
@objc open var trailingTextFont = UIFont.boldSystemFont(ofSize: 18) {
didSet { updateUI() }
}
@objc open var contentInset = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12) {
didSet {
guard contentView.superview != nil else { return }
contentView.removeFromSuperview()
addSubview(contentView)
contentView.pinToSuperview(insets: contentInset)
updateUI()
}
}
@available(*, deprecated, renamed: "contentInset")
@objc open var labelMargin = CGFloat(12.0) {
didSet {
contentInset = UIEdgeInsets(
top: labelMargin,
left: labelMargin,
bottom: labelMargin,
right: labelMargin
)
}
}
@objc open var pressAnimationDuration = 0.1
@objc open var cornerRadius = CGFloat(10.0)
@objc open var focusedScaleFactor = CGFloat(1.05)
@objc open var shadowRadius = CGFloat(10)
@objc open var shadowColor = UIColor.black.cgColor
@objc open var focusedShadowOffset = CGSize(width: 0, height: 27)
@objc open var focusedShadowOpacity = Float(0.75)
@objc open var focusedViewAlpha = CGFloat(0.75)
@objc open var buttonWasPressed: ((String?) -> Void)?
private var textAttributes: [NSAttributedString.Key: Any] {
return [
.foregroundColor: textColor,
.font: font
]
}
private var trailingTextAttributes: [NSAttributedString.Key: Any] {
return [
.foregroundColor: trailingTextColor,
.font: trailingTextFont
]
}
public override init(frame: CGRect) {
super.init(frame: frame)
setUpUI()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUpUI()
}
override open var intrinsicContentSize: CGSize {
return label.intrinsicContentSize
}
override open var canBecomeFocused: Bool {
return isFocusable
}
override open func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
coordinator.addCoordinatedAnimations({
self.isFocused ? self.applyFocusedAppearance() : self.applyUnfocusedAppearance()
})
}
open func updateUI() {
truncateAndUpdateText()
}
// MARK: - Presses
override open func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
super.pressesBegan(presses, with: event)
for item in presses where item.type == .select {
applyPressDownAppearance()
}
}
override open func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
super.pressesEnded(presses, with: event)
for item in presses where item.type == .select {
applyPressUpAppearance()
}
}
override open func pressesCancelled(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
for item in presses where item.type == .select {
applyPressUpAppearance()
}
}
// MARK: - Private
private func setUpUI() {
setUpView()
setUpFocusedView()
setUpContentView()
setUpLabel()
setUpSelectGestureRecognizer()
applyUnfocusedAppearance()
}
private func setUpView() {
isUserInteractionEnabled = true
backgroundColor = .clear
clipsToBounds = false
isAccessibilityElement = true
accessibilityTraits = UIAccessibilityTraits.button
accessibilityIdentifier = "tvos more button"
}
private func setUpContentView() {
addSubview(contentView)
contentView.pinToSuperview(insets: contentInset)
}
private func setUpLabel() {
label = UILabel(frame: bounds)
label.numberOfLines = 0
contentView.addSubview(label)
label.pinToSuperview()
}
private func setUpFocusedView() {
focusedView = UIView(frame: bounds)
focusedView.layer.cornerRadius = cornerRadius
focusedView.layer.shadowColor = shadowColor
focusedView.layer.shadowRadius = shadowRadius
addSubview(focusedView)
focusedView.pinToSuperview()
let blurEffect = UIBlurEffect(style: .light)
let blurredView = UIVisualEffectView(effect: blurEffect)
blurredView.frame = bounds
blurredView.alpha = focusedViewAlpha
blurredView.layer.cornerRadius = cornerRadius
blurredView.layer.masksToBounds = true
focusedView.addSubview(blurredView)
blurredView.pinToSuperview()
}
private func setUpSelectGestureRecognizer() {
selectGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(selectGestureWasPressed))
selectGestureRecognizer.allowedPressTypes = [NSNumber(value: UIPress.PressType.select.rawValue)]
addGestureRecognizer(selectGestureRecognizer)
}
@objc private func selectGestureWasPressed() {
buttonWasPressed?(text)
}
// MARK: - Focus Appearance
func applyFocusedAppearance() {
transform = CGAffineTransform(scaleX: focusedScaleFactor, y: focusedScaleFactor)
focusedView.layer.shadowOffset = focusedShadowOffset
focusedView.layer.shadowOpacity = focusedShadowOpacity
focusedView.alpha = 1
}
func applyUnfocusedAppearance() {
transform = CGAffineTransform.identity
focusedView.layer.shadowOffset = .zero
focusedView.layer.shadowOpacity = 0
focusedView.alpha = 0
}
private func applyPressUpAppearance() {
UIView.animate(withDuration: pressAnimationDuration) {
self.isFocused ? self.applyFocusedAppearance() : self.applyUnfocusedAppearance()
}
}
private func applyPressDownAppearance() {
UIView.animate(withDuration: pressAnimationDuration) {
self.transform = CGAffineTransform.identity
self.focusedView.layer.shadowOffset = .zero
self.focusedView.layer.shadowOpacity = 0
}
}
// MARK: - Truncating Text
private func truncateAndUpdateText() {
label.text = text
accessibilityLabel = text
guard let text = text, !text.isEmpty else { return }
layoutIfNeeded()
let labelSize = label.bounds.size
let trailingText = " " + self.trailingText
label.attributedText = text.truncateToSize(size: labelSize,
ellipsesString: ellipsesString,
trailingText: trailingText,
attributes: textAttributes,
trailingTextAttributes: trailingTextAttributes)
accessibilityLabel = label.attributedText?.string
if case .auto = focusableMode {
isFocusable = !text.willFit(to: labelSize,
attributes: textAttributes,
trailingTextAttributes: trailingTextAttributes)
}
}
}
| mit | dc256b7d0e28dd77bf1620be6dd24560 | 30.838006 | 120 | 0.629746 | 5.164224 | false | false | false | false |
e78l/swift-corelibs-foundation | Foundation/URLSession/libcurl/MultiHandle.swift | 1 | 19938 | //
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
// -----------------------------------------------------------------------------
///
/// libcurl *multi handle* wrapper.
/// These are libcurl helpers for the URLSession API code.
/// - SeeAlso: https://curl.haxx.se/libcurl/c/
/// - SeeAlso: URLSession.swift
///
// -----------------------------------------------------------------------------
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
import SwiftFoundation
#else
import Foundation
#endif
import CoreFoundation
import CFURLSessionInterface
import Dispatch
extension URLSession {
/// Minimal wrapper around [curl multi interface](https://curl.haxx.se/libcurl/c/libcurl-multi.html).
///
/// The the *multi handle* manages the sockets for easy handles
/// (`_EasyHandle`), and this implementation uses
/// libdispatch to listen for sockets being read / write ready.
///
/// Using `DispatchSource` allows this implementation to be
/// non-blocking and all code to run on the same thread /
/// `DispatchQueue` -- thus keeping is simple.
///
/// - SeeAlso: _EasyHandle
internal final class _MultiHandle {
let rawHandle = CFURLSessionMultiHandleInit()
let queue: DispatchQueue
let group = DispatchGroup()
fileprivate var easyHandles: [_EasyHandle] = []
fileprivate var timeoutSource: _TimeoutSource? = nil
private var reentrantInUpdateTimeoutTimer = false
init(configuration: URLSession._Configuration, workQueue: DispatchQueue) {
queue = DispatchQueue(label: "MultiHandle.isolation", target: workQueue)
setupCallbacks()
configure(with: configuration)
}
deinit {
// C.f.: <https://curl.haxx.se/libcurl/c/curl_multi_cleanup.html>
easyHandles.forEach {
try! CFURLSessionMultiHandleRemoveHandle(rawHandle, $0.rawHandle).asError()
}
try! CFURLSessionMultiHandleDeinit(rawHandle).asError()
}
}
}
extension URLSession._MultiHandle {
func configure(with configuration: URLSession._Configuration) {
try! CFURLSession_multi_setopt_l(rawHandle, CFURLSessionMultiOptionMAX_HOST_CONNECTIONS, numericCast(configuration.httpMaximumConnectionsPerHost)).asError()
try! CFURLSession_multi_setopt_l(rawHandle, CFURLSessionMultiOptionPIPELINING, configuration.httpShouldUsePipelining ? 3 : 2).asError()
//TODO: We may want to set
// CFURLSessionMultiOptionMAXCONNECTS
// CFURLSessionMultiOptionMAX_TOTAL_CONNECTIONS
}
}
fileprivate extension URLSession._MultiHandle {
static func from(callbackUserData userdata: UnsafeMutableRawPointer?) -> URLSession._MultiHandle? {
guard let userdata = userdata else { return nil }
return Unmanaged<URLSession._MultiHandle>.fromOpaque(userdata).takeUnretainedValue()
}
}
fileprivate extension URLSession._MultiHandle {
/// Forward the libcurl callbacks into Swift methods
func setupCallbacks() {
// Socket
try! CFURLSession_multi_setopt_ptr(rawHandle, CFURLSessionMultiOptionSOCKETDATA, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())).asError()
try! CFURLSession_multi_setopt_sf(rawHandle, CFURLSessionMultiOptionSOCKETFUNCTION) { (easyHandle: CFURLSessionEasyHandle, socket: CFURLSession_socket_t, what: Int32, userdata: UnsafeMutableRawPointer?, socketptr: UnsafeMutableRawPointer?) -> Int32 in
guard let handle = URLSession._MultiHandle.from(callbackUserData: userdata) else { fatalError() }
return handle.register(socket: socket, for: easyHandle, what: what, socketSourcePtr: socketptr)
}.asError()
// Timeout:
try! CFURLSession_multi_setopt_ptr(rawHandle, CFURLSessionMultiOptionTIMERDATA, UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())).asError()
#if os(Windows) && (arch(arm64) || arch(x86_64))
typealias CFURLSessionMultiOption = Int32
#else
typealias CFURLSessionMultiOption = Int
#endif
try! CFURLSession_multi_setopt_tf(rawHandle, CFURLSessionMultiOptionTIMERFUNCTION) { (_, timeout: CFURLSessionMultiOption, userdata: UnsafeMutableRawPointer?) -> Int32 in
guard let handle = URLSession._MultiHandle.from(callbackUserData: userdata) else { fatalError() }
handle.updateTimeoutTimer(to: numericCast(timeout))
return 0
}.asError()
}
/// <https://curl.haxx.se/libcurl/c/CURLMOPT_SOCKETFUNCTION.html> and
/// <https://curl.haxx.se/libcurl/c/curl_multi_socket_action.html>
func register(socket: CFURLSession_socket_t, for easyHandle: CFURLSessionEasyHandle, what: Int32, socketSourcePtr: UnsafeMutableRawPointer?) -> Int32 {
// We get this callback whenever we need to register or unregister a
// given socket with libdispatch.
// The `action` / `what` defines if we should register or unregister
// that we're interested in read and/or write readiness. We will do so
// through libdispatch (DispatchSource) and store the source(s) inside
// a `SocketSources` which we in turn store inside libcurl's multi handle
// by means of curl_multi_assign() -- we retain the object fist.
let action = _SocketRegisterAction(rawValue: CFURLSessionPoll(value: what))
var socketSources = _SocketSources.from(socketSourcePtr: socketSourcePtr)
if socketSources == nil && action.needsSource {
let s = _SocketSources()
let p = Unmanaged.passRetained(s).toOpaque()
CFURLSessionMultiHandleAssign(rawHandle, socket, UnsafeMutableRawPointer(p))
socketSources = s
} else if socketSources != nil && action == .unregister {
// We need to release the stored pointer:
if let opaque = socketSourcePtr {
Unmanaged<_SocketSources>.fromOpaque(opaque).release()
}
socketSources = nil
}
if let ss = socketSources {
let handler = DispatchWorkItem { [weak self] in
self?.performAction(for: socket)
}
ss.createSources(with: action, socket: socket, queue: queue, handler: handler)
}
return 0
}
/// What read / write ready event to register / unregister.
///
/// This re-maps `CFURLSessionPoll` / `CURL_POLL`.
enum _SocketRegisterAction {
case none
case registerRead
case registerWrite
case registerReadAndWrite
case unregister
}
}
internal extension URLSession._MultiHandle {
/// Add an easy handle -- start its transfer.
func add(_ handle: _EasyHandle) {
// If this is the first handle being added, we need to `kick` the
// underlying multi handle by calling `timeoutTimerFired` as
// described in
// <https://curl.haxx.se/libcurl/c/curl_multi_socket_action.html>.
// That will initiate the registration for timeout timer and socket
// readiness.
let needsTimeout = self.easyHandles.isEmpty
self.easyHandles.append(handle)
try! CFURLSessionMultiHandleAddHandle(self.rawHandle, handle.rawHandle).asError()
if needsTimeout {
self.timeoutTimerFired()
}
}
/// Remove an easy handle -- stop its transfer.
func remove(_ handle: _EasyHandle) {
guard let idx = self.easyHandles.firstIndex(of: handle) else {
fatalError("Handle not in list.")
}
self.easyHandles.remove(at: idx)
try! CFURLSessionMultiHandleRemoveHandle(self.rawHandle, handle.rawHandle).asError()
}
}
fileprivate extension URLSession._MultiHandle {
/// This gets called when we should ask curl to perform action on a socket.
func performAction(for socket: CFURLSession_socket_t) {
try! readAndWriteAvailableData(on: socket)
}
/// This gets called when our timeout timer fires.
///
/// libcurl relies on us calling curl_multi_socket_action() every now and then.
func timeoutTimerFired() {
try! readAndWriteAvailableData(on: CFURLSessionSocketTimeout)
}
/// reads/writes available data given an action
func readAndWriteAvailableData(on socket: CFURLSession_socket_t) throws {
var runningHandlesCount = Int32(0)
try CFURLSessionMultiHandleAction(rawHandle, socket, 0, &runningHandlesCount).asError()
//TODO: Do we remove the timeout timer here if / when runningHandles == 0 ?
readMessages()
}
/// Check the status of all individual transfers.
///
/// libcurl refers to this as “read multi stack informationals”.
/// Check for transfers that completed.
func readMessages() {
// We pop the messages one by one in a loop:
repeat {
// count will contain the messages left in the queue
var count = Int32(0)
let info = CFURLSessionMultiHandleInfoRead(rawHandle, &count)
guard let handle = info.easyHandle else { break }
let code = info.resultCode
completedTransfer(forEasyHandle: handle, easyCode: code)
} while true
}
/// Transfer completed.
func completedTransfer(forEasyHandle handle: CFURLSessionEasyHandle, easyCode: CFURLSessionEasyCode) {
// Look up the matching wrapper:
guard let idx = easyHandles.firstIndex(where: { $0.rawHandle == handle }) else {
fatalError("Transfer completed for easy handle, but it is not in the list of added handles.")
}
let easyHandle = easyHandles[idx]
// Find the NSURLError code
var error: NSError?
if let errorCode = easyHandle.urlErrorCode(for: easyCode) {
var errorDescription: String = ""
if easyHandle.errorBuffer[0] == 0 {
let description = CFURLSessionEasyCodeDescription(easyCode)!
errorDescription = NSString(bytes: UnsafeMutableRawPointer(mutating: description), length: strlen(description), encoding: String.Encoding.utf8.rawValue)! as String
} else {
errorDescription = String(cString: easyHandle.errorBuffer)
}
error = NSError(domain: NSURLErrorDomain, code: errorCode, userInfo: [
NSLocalizedDescriptionKey: errorDescription
])
}
completedTransfer(forEasyHandle: easyHandle, error: error)
}
/// Transfer completed.
func completedTransfer(forEasyHandle handle: _EasyHandle, error: NSError?) {
handle.completedTransfer(withError: error)
}
}
fileprivate extension _EasyHandle {
/// An error code within the `NSURLErrorDomain` based on the error of the
/// easy handle.
/// - Note: The error value is set only on failure. You can't use it to
/// determine *if* something failed or not, only *why* it failed.
func urlErrorCode(for easyCode: CFURLSessionEasyCode) -> Int? {
switch (easyCode, CInt(connectFailureErrno)) {
case (CFURLSessionEasyCodeOK, _):
return nil
case (_, ECONNREFUSED):
return NSURLErrorCannotConnectToHost
case (CFURLSessionEasyCodeUNSUPPORTED_PROTOCOL, _):
return NSURLErrorUnsupportedURL
case (CFURLSessionEasyCodeURL_MALFORMAT, _):
return NSURLErrorBadURL
case (CFURLSessionEasyCodeCOULDNT_RESOLVE_HOST, _):
// Oddly, this appears to happen for malformed URLs, too.
return NSURLErrorCannotFindHost
case (CFURLSessionEasyCodeRECV_ERROR, ECONNRESET):
return NSURLErrorNetworkConnectionLost
case (CFURLSessionEasyCodeSEND_ERROR, ECONNRESET):
return NSURLErrorNetworkConnectionLost
case (CFURLSessionEasyCodeGOT_NOTHING, _):
return NSURLErrorBadServerResponse
case (CFURLSessionEasyCodeABORTED_BY_CALLBACK, _):
return NSURLErrorUnknown // Or NSURLErrorCancelled if we're in such a state
case (CFURLSessionEasyCodeCOULDNT_CONNECT, ETIMEDOUT):
return NSURLErrorTimedOut
case (CFURLSessionEasyCodeOPERATION_TIMEDOUT, _):
return NSURLErrorTimedOut
default:
//TODO: Need to map to one of the NSURLError... constants
return NSURLErrorUnknown
}
}
}
fileprivate extension URLSession._MultiHandle._SocketRegisterAction {
init(rawValue: CFURLSessionPoll) {
switch rawValue {
case CFURLSessionPollNone:
self = .none
case CFURLSessionPollIn:
self = .registerRead
case CFURLSessionPollOut:
self = .registerWrite
case CFURLSessionPollInOut:
self = .registerReadAndWrite
case CFURLSessionPollRemove:
self = .unregister
default:
fatalError("Invalid CFURLSessionPoll value.")
}
}
}
extension CFURLSessionPoll : Equatable {
public static func ==(lhs: CFURLSessionPoll, rhs: CFURLSessionPoll) -> Bool {
return lhs.value == rhs.value
}
}
fileprivate extension URLSession._MultiHandle._SocketRegisterAction {
/// Should a libdispatch source be registered for **read** readiness?
var needsReadSource: Bool {
switch self {
case .none: return false
case .registerRead: return true
case .registerWrite: return false
case .registerReadAndWrite: return true
case .unregister: return false
}
}
/// Should a libdispatch source be registered for **write** readiness?
var needsWriteSource: Bool {
switch self {
case .none: return false
case .registerRead: return false
case .registerWrite: return true
case .registerReadAndWrite: return true
case .unregister: return false
}
}
/// Should either a **read** or a **write** readiness libdispatch source be
/// registered?
var needsSource: Bool {
return needsReadSource || needsWriteSource
}
}
/// A helper class that wraps a libdispatch timer.
///
/// Used to implement the timeout of `URLSession.MultiHandle` and `URLSession.EasyHandle`
class _TimeoutSource {
let rawSource: DispatchSource
let milliseconds: Int
let queue: DispatchQueue //needed to restart the timer for EasyHandles
let handler: DispatchWorkItem //needed to restart the timer for EasyHandles
init(queue: DispatchQueue, milliseconds: Int, handler: DispatchWorkItem) {
self.queue = queue
self.handler = handler
self.milliseconds = milliseconds
self.rawSource = DispatchSource.makeTimerSource(queue: queue) as! DispatchSource
let delay = UInt64(max(1, milliseconds - 1))
let start = DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(delay))
rawSource.schedule(deadline: start, repeating: .milliseconds(Int(delay)), leeway: (milliseconds == 1) ? .microseconds(Int(1)) : .milliseconds(Int(1)))
rawSource.setEventHandler(handler: handler)
rawSource.resume()
}
deinit {
rawSource.cancel()
}
}
fileprivate extension URLSession._MultiHandle {
/// <https://curl.haxx.se/libcurl/c/CURLMOPT_TIMERFUNCTION.html>
func updateTimeoutTimer(to value: Int) {
updateTimeoutTimer(to: _Timeout(timeout: value))
}
func updateTimeoutTimer(to timeout: _Timeout) {
// Set up a timeout timer based on the given value:
switch timeout {
case .none:
timeoutSource = nil
case .immediate:
timeoutSource = nil
queue.async { self.timeoutTimerFired() }
case .milliseconds(let milliseconds):
if (timeoutSource == nil) || timeoutSource!.milliseconds != milliseconds {
//TODO: Could simply change the existing timer by using DispatchSourceTimer again.
let block = DispatchWorkItem { [weak self] in
self?.timeoutTimerFired()
}
timeoutSource = _TimeoutSource(queue: queue, milliseconds: milliseconds, handler: block)
}
}
}
enum _Timeout {
case milliseconds(Int)
case none
case immediate
}
}
fileprivate extension URLSession._MultiHandle._Timeout {
init(timeout: Int) {
switch timeout {
case -1:
self = .none
case 0:
self = .immediate
default:
self = .milliseconds(timeout)
}
}
}
/// Read and write libdispatch sources for a specific socket.
///
/// A simple helper that combines two sources -- both being optional.
///
/// This info is stored into the socket using `curl_multi_assign()`.
///
/// - SeeAlso: URLSession.MultiHandle.SocketRegisterAction
fileprivate class _SocketSources {
var readSource: DispatchSource?
var writeSource: DispatchSource?
func createReadSource(socket: CFURLSession_socket_t, queue: DispatchQueue, handler: DispatchWorkItem) {
guard readSource == nil else { return }
#if os(Windows)
let s = DispatchSource.makeReadSource(handle: HANDLE(bitPattern: Int(socket))!, queue: queue)
#else
let s = DispatchSource.makeReadSource(fileDescriptor: socket, queue: queue)
#endif
s.setEventHandler(handler: handler)
readSource = s as? DispatchSource
s.resume()
}
func createWriteSource(socket: CFURLSession_socket_t, queue: DispatchQueue, handler: DispatchWorkItem) {
guard writeSource == nil else { return }
#if os(Windows)
let s = DispatchSource.makeWriteSource(handle: HANDLE(bitPattern: Int(socket))!, queue: queue)
#else
let s = DispatchSource.makeWriteSource(fileDescriptor: socket, queue: queue)
#endif
s.setEventHandler(handler: handler)
writeSource = s as? DispatchSource
s.resume()
}
func tearDown() {
if let s = readSource {
s.cancel()
}
readSource = nil
if let s = writeSource {
s.cancel()
}
writeSource = nil
}
}
extension _SocketSources {
/// Create a read and/or write source as specified by the action.
func createSources(with action: URLSession._MultiHandle._SocketRegisterAction, socket: CFURLSession_socket_t, queue: DispatchQueue, handler: DispatchWorkItem) {
if action.needsReadSource {
createReadSource(socket: socket, queue: queue, handler: handler)
}
if action.needsWriteSource {
createWriteSource(socket: socket, queue: queue, handler: handler)
}
}
}
extension _SocketSources {
/// Unwraps the `SocketSources`
///
/// A `SocketSources` is stored into the multi handle's socket using
/// `curl_multi_assign()`. This helper unwraps it from the returned
/// `UnsafeMutablePointer<Void>`.
static func from(socketSourcePtr ptr: UnsafeMutableRawPointer?) -> _SocketSources? {
guard let ptr = ptr else { return nil }
return Unmanaged<_SocketSources>.fromOpaque(ptr).takeUnretainedValue()
}
}
extension CFURLSessionMultiCode : Equatable {
public static func ==(lhs: CFURLSessionMultiCode, rhs: CFURLSessionMultiCode) -> Bool {
return lhs.value == rhs.value
}
}
extension CFURLSessionMultiCode : Error {
public var _domain: String { return "libcurl.Multi" }
public var _code: Int { return Int(self.value) }
}
internal extension CFURLSessionMultiCode {
func asError() throws {
if self == CFURLSessionMultiCodeOK { return }
throw self
}
}
| apache-2.0 | 32adf2ed4ce6ec2a69263682cbb74db6 | 40.18595 | 259 | 0.656767 | 4.740547 | false | false | false | false |
ulusoyca/SwiftData | SwiftData.swift | 1 | 62823 | //
// SwiftData.swift
//
// Copyright (c) 2015 Ryan Fowler
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
// MARK: - SwiftData
public struct SwiftData {
// MARK: - Public SwiftData Functions
// MARK: - Execute Statements
/**
Execute a non-query SQL statement (e.g. INSERT, UPDATE, DELETE, etc.)
This function will execute the provided SQL and return an Int with the error code, or nil if there was no error.
It is recommended to always verify that the return value is nil to ensure that the operation was successful.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:param: sqlStr The non-query string of SQL to be executed (INSERT, UPDATE, DELETE, etc.)
:returns: An Int with the error code, or nil if there was no error
*/
public static func executeChange(sqlStr: String) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.executeChange(sqlStr)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Execute a non-query SQL statement (e.g. INSERT, UPDATE, DELETE, etc.) along with arguments to be bound to the characters "?" (for values) and "i?" (for identifiers e.g. table or column names).
The objects in the provided array of arguments will be bound, in order, to the "i?" and "?" characters in the SQL string.
The quantity of "i?"s and "?"s in the SQL string must be equal to the quantity of arguments provided.
Objects that are to bind as! an identifier ("i?") must be of type String.
Identifiers should be bound and escaped if provided by the user.
If "nil" is provided as! an argument, the NULL value will be bound to the appropriate value in the SQL string.
For more information on how the objects will be escaped, refer to the functions "escapeValue()" and "escapeIdentifier()".
Note that the "escapeValue()" and "escapeIdentifier()" include the necessary quotations ' ' or " " to the arguments when being bound to the SQL.
It is recommended to always verify that the return value is nil to ensure that the operation was successful.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- binding errors (201 - 203)
:param: sqlStr The non-query string of SQL to be executed (INSERT, UPDATE, DELETE, etc.)
:param: withArgs An array of objects to bind to the "?" and "i?" characters in the sqlStr
:returns: An Int with the error code, or nil if there was no error
*/
public static func executeChange(sqlStr: String, withArgs: [AnyObject]) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.executeChange(sqlStr, withArgs: withArgs)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Execute multiple SQL statements (non-queries e.g. INSERT, UPDATE, DELETE, etc.)
This function will execute each SQL statment in the provided array, in order, and return an Int with the error code, or nil if there was no error.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:param: sqlArr An array of non-query strings of SQL to be executed (INSERT, UPDATE, DELETE, etc.)
:returns: An Int with the error code, or nil if there was no error
*/
public static func executeMultipleChanges(sqlArr: [String]) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
for sqlStr in sqlArr {
if let err = SQLiteDB.sharedInstance.executeChange(sqlStr) {
SQLiteDB.sharedInstance.close()
if let index = sqlArr.indexOf(sqlStr) {
print("Error occurred on array item: \(index) -> \"\(sqlStr)\"")
}
error = err
return
}
}
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Execute a SQLite query statement (e.g. SELECT)
This function will execute the provided SQL and return a tuple of:
- an Array of SDRow objects
- an Int with the error code, or nil if there was no error
The value for each column in an SDRow can be obtained using the column name in the subscript format similar to a Dictionary, along with the function to obtain the value in the appropriate type (.asString(), .asDate(), .asData(), .asInt(), .asDouble(), and .asBool()).
Without the function call to return a specific type, the SDRow will return an object with type AnyObject.
Note: NULL values in the SQLite database will be returned as! 'nil'.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:param: sqlStr The query String of SQL to be executed (e.g. SELECT)
:returns: A tuple containing an Array of "SDRow"s, and an Int with the error code or nil if there was no error
*/
public static func executeQuery(sqlStr: String) -> (result: [SDRow], error: Int?) {
var result = [SDRow] ()
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
(result, error) = SQLiteDB.sharedInstance.executeQuery(sqlStr)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
/**
Execute a SQL query statement (e.g. SELECT) with arguments to be bound to the characters "?" (for values) and "i?" (for identifiers e.g. table or column names).
See the "executeChange(sqlStr: String, withArgs: [AnyObject?])" function for more information on the arguments provided and binding.
See the "executeQuery(sqlStr: String)" function for more information on the return value.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- binding errors (201 - 203)
:param: sqlStr The query String of SQL to be executed (e.g. SELECT)
:param: withArgs An array of objects that will be bound, in order, to the characters "?" (for values) and "i?" (for identifiers, e.g. table or column names) in the sqlStr.
:returns: A tuple containing an Array of "SDRow"s, and an Int with the error code or nil if there was no error
*/
public static func executeQuery(sqlStr: String, withArgs: [AnyObject]) -> (result: [SDRow], error: Int?) {
var result = [SDRow] ()
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
(result, error) = SQLiteDB.sharedInstance.executeQuery(sqlStr, withArgs: withArgs)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
/**
Execute functions in a closure on a single custom connection
Note: This function cannot be nested within itself, or inside a transaction/savepoint.
Possible errors returned by this function are:
- custom connection errors (301 - 306)
:param: flags The custom flag associated with the connection. Can be either:
- .ReadOnly
- .ReadWrite
- .ReadWriteCreate
:param: closure A closure containing functions that will be executed on the custom connection
:returns: An Int with the error code, or nil if there was no error
*/
public static func executeWithConnection(flags: SD.Flags, closure: ()->Void) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.openWithFlags(flags.toSQL()) {
error = err
return
}
closure()
if let err = SQLiteDB.sharedInstance.closeCustomConnection() {
error = err
return
}
}
putOnThread(task)
return error
}
// MARK: - Escaping Objects
/**
Escape an object to be inserted into a SQLite statement as! a value
NOTE: Supported object types are: String, Int, Double, Bool, NSData, NSDate, and nil. All other data types will return the String value "NULL", and a warning message will be printed.
:param: obj The value to be escaped
:returns: The escaped value as! a String, ready to be inserted into a SQL statement. Note: Single quotes (') will be placed around the entire value, if necessary.
*/
public static func escapeValue(obj: AnyObject?) -> String {
return SQLiteDB.sharedInstance.escapeValue(obj)
}
/**
Escape a string to be inserted into a SQLite statement as! an indentifier (e.g. table or column name)
:param: obj The identifier to be escaped. NOTE: This object must be of type String.
:returns: The escaped identifier as! a String, ready to be inserted into a SQL statement. Note: Double quotes (") will be placed around the entire identifier.
*/
public static func escapeIdentifier(obj: String) -> String {
return SQLiteDB.sharedInstance.escapeIdentifier(obj)
}
// MARK: - Tables
/**
Create A Table With The Provided Column Names and Types
Note: The ID field is created automatically as! "INTEGER PRIMARY KEY AUTOINCREMENT"
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:param: table The table name to be created
:param: columnNamesAndTypes A dictionary where the key = column name, and the value = data type
:returns: An Int with the error code, or nil if there was no error
*/
public static func createTable(table: String, withColumnNamesAndTypes values: [String: SwiftData.DataType]) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.createSQLTable(table, withColumnsAndTypes: values)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Delete a SQLite table by name
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:param: table The table name to be deleted
:returns: An Int with the error code, or nil if there was no error
*/
public static func deleteTable(table: String) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.deleteSQLTable(table)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Obtain a list of the existing SQLite table names
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- Table query error (403)
:returns: A tuple containing an Array of all existing SQLite table names, and an Int with the error code or nil if there was no error
*/
public static func existingTables() -> (result: [String], error: Int?) {
var result = [String] ()
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
(result, error) = SQLiteDB.sharedInstance.existingTables()
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
// MARK: - Misc
/**
Obtain the error message relating to the provided error code
:param: code The error code provided
:returns: The error message relating to the provided error code
*/
public static func errorMessageForCode(code: Int) -> String {
return SwiftData.SDError.errorMessageFromCode(code)
}
/**
Obtain the database path
:returns: The path to the SwiftData database
*/
public static func databasePath() -> String {
return SQLiteDB.sharedInstance.dbPath
}
/**
Obtain the last inserted row id
Note: Care should be taken when the database is being accessed from multiple threads. The value could possibly return the last inserted row ID for another operation if another thread executes after your intended operation but before this function call.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:returns: A tuple of he ID of the last successfully inserted row's, and an Int of the error code or nil if there was no error
*/
public static func lastInsertedRowID() -> (rowID: Int, error: Int?) {
var result = 0
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
result = SQLiteDB.sharedInstance.lastInsertedRowID()
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
/**
Obtain the number of rows modified by the most recently completed SQLite statement (INSERT, UPDATE, or DELETE)
Note: Care should be taken when the database is being accessed from multiple threads. The value could possibly return the number of rows modified for another operation if another thread executes after your intended operation but before this function call.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:returns: A tuple of the number of rows modified by the most recently completed SQLite statement, and an Int with the error code or nil if there was no error
*/
public static func numberOfRowsModified() -> (rowID: Int, error: Int?) {
var result = 0
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
result = SQLiteDB.sharedInstance.numberOfRowsModified()
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
// MARK: - Indexes
/**
Create a SQLite index on the specified table and column(s)
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- Index error (401)
:param: name The index name that is being created
:param: onColumns An array of column names that the index will be applied to (must be one column or greater)
:param: inTable The table name where the index is being created
:param: isUnique True if the index should be unique, false if it should not be unique (defaults to false)
:returns: An Int with the error code, or nil if there was no error
*/
public static func createIndex(name name: String, onColumns: [String], inTable: String, isUnique: Bool = false) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.createIndex(name, columns: onColumns, table: inTable, unique: isUnique)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Remove a SQLite index by its name
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:param: indexName The name of the index to be removed
:returns: An Int with the error code, or nil if there was no error
*/
public static func removeIndex(indexName: String) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
error = SQLiteDB.sharedInstance.removeIndex(indexName)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Obtain a list of all existing indexes
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- Index error (402)
:returns: A tuple containing an Array of all existing index names on the SQLite database, and an Int with the error code or nil if there was no error
*/
public static func existingIndexes() -> (result: [String], error: Int?) {
var result = [String] ()
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
(result, error) = SQLiteDB.sharedInstance.existingIndexes()
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
/**
Obtain a list of all existing indexes on a specific table
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- Index error (402)
:param: table The name of the table that is being queried for indexes
:returns: A tuple containing an Array of all existing index names in the table, and an Int with the error code or nil if there was no error
*/
public static func existingIndexesForTable(table: String) -> (result: [String], error: Int?) {
var result = [String] ()
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
(result, error) = SQLiteDB.sharedInstance.existingIndexesForTable(table)
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return (result, error)
}
// MARK: - Transactions and Savepoints
/**
Execute commands within a single exclusive transaction
A connection to the database is opened and is not closed until the end of the transaction. A transaction cannot be embedded into another transaction or savepoint.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
- Transaction errors (501 - 502)
:param: transactionClosure A closure containing commands that will execute as! part of a single transaction. If the transactionClosure returns true, the changes made within the closure will be committed. If false, the changes will be rolled back and will not be saved.
:returns: An Int with the error code, or nil if there was no error committing or rolling back the transaction
*/
public static func transaction(transactionClosure: ()->Bool) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
if let err = SQLiteDB.sharedInstance.beginTransaction() {
SQLiteDB.sharedInstance.close()
error = err
return
}
if transactionClosure() {
if let err = SQLiteDB.sharedInstance.commitTransaction() {
error = err
}
} else {
if let err = SQLiteDB.sharedInstance.rollbackTransaction() {
error = err
}
}
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Execute commands within a single savepoint
A connection to the database is opened and is not closed until the end of the savepoint (or the end of the last savepoint, if embedded).
NOTE: Unlike transactions, savepoints may be embedded into other savepoints or transactions.
Possible errors returned by this function are:
- SQLite errors (0 - 101)
:param: savepointClosure A closure containing commands that will execute as! part of a single savepoint. If the savepointClosure returns true, the changes made within the closure will be released. If false, the changes will be rolled back and will not be saved.
:returns: An Int with the error code, or nil if there was no error releasing or rolling back the savepoint
*/
public static func savepoint(savepointClosure: ()->Bool) -> Int? {
var error: Int? = nil
let task: ()->Void = {
if let err = SQLiteDB.sharedInstance.open() {
error = err
return
}
if let err = SQLiteDB.sharedInstance.beginSavepoint() {
SQLiteDB.sharedInstance.close()
error = err
return
}
if savepointClosure() {
if let err = SQLiteDB.sharedInstance.releaseSavepoint() {
error = err
}
} else {
if let err = SQLiteDB.sharedInstance.rollbackSavepoint() {
print("Error rolling back to savepoint")
--SQLiteDB.sharedInstance.savepointsOpen
SQLiteDB.sharedInstance.close()
error = err
return
}
if let err = SQLiteDB.sharedInstance.releaseSavepoint() {
error = err
}
}
SQLiteDB.sharedInstance.close()
}
putOnThread(task)
return error
}
/**
Convenience function to save a UIImage to disk and return the ID
:param: image The UIImage to be saved
:returns: The ID of the saved image as! a String, or nil if there was an error saving the image to disk
*/
public static func saveUIImage(image: UIImage) -> String? {
let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
let imageDirPath = NSURL(fileURLWithPath: docsPath).URLByAppendingPathComponent("SwiftDataImages")
if !NSFileManager.defaultManager().fileExistsAtPath(imageDirPath.absoluteString) {
do {
try NSFileManager.defaultManager().createDirectoryAtPath(imageDirPath.absoluteString, withIntermediateDirectories: false, attributes: nil)
} catch _ {
print("Error creating SwiftData image folder")
return nil
}
}
let imageID = NSUUID().UUIDString
let imagePath = imageDirPath.URLByAppendingPathComponent(imageID).absoluteString
let imageAsData = UIImagePNGRepresentation(image)
if !imageAsData!.writeToFile(imagePath, atomically: true) {
print("Error saving image")
return nil
}
return imageID
}
/**
Convenience function to delete a UIImage with the specified ID
:param: id The id of the UIImage
:returns: True if the image was successfully deleted, or false if there was an error during the deletion
*/
public static func deleteUIImageWithID(id: String) -> Bool {
let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
let imageDirPath = NSURL(fileURLWithPath: docsPath).URLByAppendingPathComponent("SwiftDataImages")
let fullPath = imageDirPath.URLByAppendingPathComponent(id).absoluteString
do {
try NSFileManager.defaultManager().removeItemAtPath(fullPath)
return true
} catch _ as NSError {
return false
}
}
// MARK: - SQLiteDB Class
private class SQLiteDB {
class var sharedInstance: SQLiteDB {
struct Singleton {
static let instance = SQLiteDB()
}
return Singleton.instance
}
var sqliteDB: COpaquePointer = nil
var dbPath = SQLiteDB.createPath()
var inTransaction = false
var isConnected = false
var openWithFlags = false
var savepointsOpen = 0
let queue = dispatch_queue_create("SwiftData.DatabaseQueue", DISPATCH_QUEUE_SERIAL)
// MARK: - Database Handling Functions
//open a connection to the sqlite3 database
func open() -> Int? {
if inTransaction || openWithFlags || savepointsOpen > 0 {
return nil
}
if sqliteDB != nil || isConnected {
return nil
}
let status = sqlite3_open(dbPath.cStringUsingEncoding(NSUTF8StringEncoding)!, &sqliteDB)
if status != SQLITE_OK {
print("SwiftData Error -> During: Opening Database")
print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
print(" -> Details: \(errMsg)")
}
return Int(status)
}
isConnected = true
return nil
}
//open a connection to the sqlite3 database with flags
func openWithFlags(flags: Int32) -> Int? {
if inTransaction {
print("SwiftData Error -> During: Opening Database with Flags")
print(" -> Code: 302 - Cannot open a custom connection inside a transaction")
return 302
}
if openWithFlags {
print("SwiftData Error -> During: Opening Database with Flags")
print(" -> Code: 301 - A custom connection is already open")
return 301
}
if savepointsOpen > 0 {
print("SwiftData Error -> During: Opening Database with Flags")
print(" -> Code: 303 - Cannot open a custom connection inside a savepoint")
return 303
}
if isConnected {
print("SwiftData Error -> During: Opening Database with Flags")
print(" -> Code: 301 - A custom connection is already open")
return 301
}
let status = sqlite3_open_v2(dbPath.cStringUsingEncoding(NSUTF8StringEncoding)!, &sqliteDB, flags, nil)
if status != SQLITE_OK {
print("SwiftData Error -> During: Opening Database with Flags")
print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
print(" -> Details: \(errMsg)")
}
return Int(status)
}
isConnected = true
openWithFlags = true
return nil
}
//close the connection to to the sqlite3 database
func close() {
if inTransaction || openWithFlags || savepointsOpen > 0 {
return
}
if sqliteDB == nil || !isConnected {
return
}
let status = sqlite3_close(sqliteDB)
if status != SQLITE_OK {
print("SwiftData Error -> During: Closing Database")
print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
print(" -> Details: \(errMsg)")
}
}
sqliteDB = nil
isConnected = false
}
//close a custom connection to the sqlite3 database
func closeCustomConnection() -> Int? {
if inTransaction {
print("SwiftData Error -> During: Closing Database with Flags")
print(" -> Code: 305 - Cannot close a custom connection inside a transaction")
return 305
}
if savepointsOpen > 0 {
print("SwiftData Error -> During: Closing Database with Flags")
print(" -> Code: 306 - Cannot close a custom connection inside a savepoint")
return 306
}
if !openWithFlags {
print("SwiftData Error -> During: Closing Database with Flags")
print(" -> Code: 304 - A custom connection is not currently open")
return 304
}
let status = sqlite3_close(sqliteDB)
sqliteDB = nil
isConnected = false
openWithFlags = false
if status != SQLITE_OK {
print("SwiftData Error -> During: Closing Database with Flags")
print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
print(" -> Details: \(errMsg)")
}
return Int(status)
}
return nil
}
//create the database path
class func createPath() -> String {
let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
let databaseStr = "SwiftData.sqlite"
let dbPath = NSURL(fileURLWithPath: docsPath).URLByAppendingPathComponent(databaseStr).absoluteString
return dbPath
}
//begin a transaction
func beginTransaction() -> Int? {
if savepointsOpen > 0 {
print("SwiftData Error -> During: Beginning Transaction")
print(" -> Code: 501 - Cannot begin a transaction within a savepoint")
return 501
}
if inTransaction {
print("SwiftData Error -> During: Beginning Transaction")
print(" -> Code: 502 - Cannot begin a transaction within another transaction")
return 502
}
if let error = executeChange("BEGIN EXCLUSIVE") {
return error
}
inTransaction = true
return nil
}
//rollback a transaction
func rollbackTransaction() -> Int? {
let error = executeChange("ROLLBACK")
inTransaction = false
return error
}
//commit a transaction
func commitTransaction() -> Int? {
let error = executeChange("COMMIT")
inTransaction = false
if let err = error {
rollbackTransaction()
return err
}
return nil
}
//begin a savepoint
func beginSavepoint() -> Int? {
if let error = executeChange("SAVEPOINT 'savepoint\(savepointsOpen + 1)'") {
return error
}
++savepointsOpen
return nil
}
//rollback a savepoint
func rollbackSavepoint() -> Int? {
return executeChange("ROLLBACK TO 'savepoint\(savepointsOpen)'")
}
//release a savepoint
func releaseSavepoint() -> Int? {
let error = executeChange("RELEASE 'savepoint\(savepointsOpen)'")
--savepointsOpen
return error
}
//get last inserted row id
func lastInsertedRowID() -> Int {
let id = sqlite3_last_insert_rowid(sqliteDB)
return Int(id)
}
//number of rows changed by last update
func numberOfRowsModified() -> Int {
return Int(sqlite3_changes(sqliteDB))
}
//return value of column
func getColumnValue(statement: COpaquePointer, index: Int32, type: String) -> AnyObject? {
switch type {
case "INT", "INTEGER", "TINYINT", "SMALLINT", "MEDIUMINT", "BIGINT", "UNSIGNED BIG INT", "INT2", "INT8":
if sqlite3_column_type(statement, index) == SQLITE_NULL {
return nil
}
return Int(sqlite3_column_int(statement, index))
case "CHARACTER(20)", "VARCHAR(255)", "VARYING CHARACTER(255)", "NCHAR(55)", "NATIVE CHARACTER", "NVARCHAR(100)", "TEXT", "CLOB":
let text = UnsafePointer<Int8>(sqlite3_column_text(statement, index))
return String.fromCString(text)
case "BLOB", "NONE":
let blob = sqlite3_column_blob(statement, index)
if blob != nil {
let size = sqlite3_column_bytes(statement, index)
return NSData(bytes: blob, length: Int(size))
}
return nil
case "REAL", "DOUBLE", "DOUBLE PRECISION", "FLOAT", "NUMERIC", "DECIMAL(10,5)":
if sqlite3_column_type(statement, index) == SQLITE_NULL {
return nil
}
return Double(sqlite3_column_double(statement, index))
case "BOOLEAN":
if sqlite3_column_type(statement, index) == SQLITE_NULL {
return nil
}
return sqlite3_column_int(statement, index) != 0
case "DATE", "DATETIME":
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
let text = UnsafePointer<Int8>(sqlite3_column_text(statement, index))
if let string = String.fromCString(text) {
return dateFormatter.dateFromString(string)
}
print("SwiftData Warning -> The text date at column: \(index) could not be cast as! a String, returning nil")
return nil
default:
print("SwiftData Warning -> Column: \(index) is of an unrecognized type, returning nil")
return nil
}
}
// MARK: SQLite Execution Functions
//execute a SQLite update from a SQL String
func executeChange(sqlStr: String, withArgs: [AnyObject]? = nil) -> Int? {
var sql = sqlStr
if let args = withArgs {
let result = bind(args, toSQL: sql)
if let error = result.error {
return error
} else {
sql = result.string
}
}
var pStmt: COpaquePointer = nil
var status = sqlite3_prepare_v2(SQLiteDB.sharedInstance.sqliteDB, sql, -1, &pStmt, nil)
if status != SQLITE_OK {
print("SwiftData Error -> During: SQL Prepare")
print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
print(" -> Details: \(errMsg)")
}
sqlite3_finalize(pStmt)
return Int(status)
}
status = sqlite3_step(pStmt)
if status != SQLITE_DONE && status != SQLITE_OK {
print("SwiftData Error -> During: SQL Step")
print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
print(" -> Details: \(errMsg)")
}
sqlite3_finalize(pStmt)
return Int(status)
}
sqlite3_finalize(pStmt)
return nil
}
//execute a SQLite query from a SQL String
func executeQuery(sqlStr: String, withArgs: [AnyObject]? = nil) -> (result: [SDRow], error: Int?) {
var resultSet = [SDRow]()
var sql = sqlStr
if let args = withArgs {
let result = bind(args, toSQL: sql)
if let err = result.error {
return (resultSet, err)
} else {
sql = result.string
}
}
var pStmt: COpaquePointer = nil
var status = sqlite3_prepare_v2(SQLiteDB.sharedInstance.sqliteDB, sql, -1, &pStmt, nil)
if status != SQLITE_OK {
print("SwiftData Error -> During: SQL Prepare")
print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
print(" -> Details: \(errMsg)")
}
sqlite3_finalize(pStmt)
return (resultSet, Int(status))
}
var columnCount: Int32 = 0
var next = true
while next {
status = sqlite3_step(pStmt)
if status == SQLITE_ROW {
columnCount = sqlite3_column_count(pStmt)
var row = SDRow()
for var i: Int32 = 0; i < columnCount; ++i {
let columnName = String.fromCString(sqlite3_column_name(pStmt, i))!
if let columnType = String.fromCString(sqlite3_column_decltype(pStmt, i))?.uppercaseString {
if let columnValue: AnyObject = getColumnValue(pStmt, index: i, type: columnType) {
row[columnName] = SDColumn(obj: columnValue)
}
} else {
var columnType = ""
switch sqlite3_column_type(pStmt, i) {
case SQLITE_INTEGER:
columnType = "INTEGER"
case SQLITE_FLOAT:
columnType = "FLOAT"
case SQLITE_TEXT:
columnType = "TEXT"
case SQLITE3_TEXT:
columnType = "TEXT"
case SQLITE_BLOB:
columnType = "BLOB"
case SQLITE_NULL:
columnType = "NULL"
default:
columnType = "NULL"
}
if let columnValue: AnyObject = getColumnValue(pStmt, index: i, type: columnType) {
row[columnName] = SDColumn(obj: columnValue)
}
}
}
resultSet.append(row)
} else if status == SQLITE_DONE {
next = false
} else {
print("SwiftData Error -> During: SQL Step")
print(" -> Code: \(status) - " + SDError.errorMessageFromCode(Int(status)))
if let errMsg = String.fromCString(sqlite3_errmsg(SQLiteDB.sharedInstance.sqliteDB)) {
print(" -> Details: \(errMsg)")
}
sqlite3_finalize(pStmt)
return (resultSet, Int(status))
}
}
sqlite3_finalize(pStmt)
return (resultSet, nil)
}
}
// MARK: - SDRow
public struct SDRow {
var values = [String: SDColumn]()
public subscript(key: String) -> SDColumn? {
get {
return values[key]
}
set(newValue) {
values[key] = newValue
}
}
}
// MARK: - SDColumn
public struct SDColumn {
var value: AnyObject
init(obj: AnyObject) {
value = obj
}
//return value by type
/**
Return the column value as! a String
:returns: An Optional String corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as! a String, or the value is NULL
*/
public func asString() -> String? {
return value as? String
}
/**
Return the column value as! an Int
:returns: An Optional Int corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as! a Int, or the value is NULL
*/
public func asInt() -> Int? {
return value as? Int
}
/**
Return the column value as! a Double
:returns: An Optional Double corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as! a Double, or the value is NULL
*/
public func asDouble() -> Double? {
return value as? Double
}
/**
Return the column value as! a Bool
:returns: An Optional Bool corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as! a Bool, or the value is NULL
*/
public func asBool() -> Bool? {
return value as? Bool
}
/**
Return the column value as! NSData
:returns: An Optional NSData object corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as! NSData, or the value is NULL
*/
public func asData() -> NSData? {
return value as? NSData
}
/**
Return the column value as! an NSDate
:returns: An Optional NSDate corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as! an NSDate, or the value is NULL
*/
public func asDate() -> NSDate? {
return value as? NSDate
}
/**
Return the column value as! an AnyObject
:returns: An Optional AnyObject corresponding to the apprioriate column value. Will be nil if: the column name does not exist, the value cannot be cast as! an AnyObject, or the value is NULL
*/
public func asAnyObject() -> AnyObject? {
return value
}
/**
Return the column value path as! a UIImage
:returns: An Optional UIImage corresponding to the path of the apprioriate column value. Will be nil if: the column name does not exist, the value of the specified path cannot be cast as! a UIImage, or the value is NULL
*/
public func asUIImage() -> UIImage? {
if let path = value as? String{
let docsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)[0]
let imageDirPath = NSURL(fileURLWithPath: docsPath).URLByAppendingPathComponent("SwiftDataImages").absoluteString
let fullPath = NSURL(fileURLWithPath: imageDirPath).URLByAppendingPathComponent(path).absoluteString
if !NSFileManager.defaultManager().fileExistsAtPath(fullPath) {
print("SwiftData Error -> Invalid image ID provided")
return nil
}
if let imageAsData = NSData(contentsOfFile: fullPath) {
return UIImage(data: imageAsData)
}
}
return nil
}
}
// MARK: - Error Handling
private struct SDError {
}
}
// MARK: - Threading
extension SwiftData {
private static func putOnThread(task: ()->Void) {
if SQLiteDB.sharedInstance.inTransaction || SQLiteDB.sharedInstance.savepointsOpen > 0 || SQLiteDB.sharedInstance.openWithFlags {
task()
} else {
dispatch_sync(SQLiteDB.sharedInstance.queue) {
task()
}
}
}
}
// MARK: - Escaping And Binding Functions
extension SwiftData.SQLiteDB {
func bind(objects: [AnyObject], toSQL sql: String) -> (string: String, error: Int?) {
var newSql = ""
var bindIndex = 0
var i = false
for char in sql.characters {
if char == "?" {
if bindIndex > objects.count - 1 {
print("SwiftData Error -> During: Object Binding")
print(" -> Code: 201 - Not enough objects to bind provided")
return ("", 201)
}
var obj = ""
if i {
if let str = objects[bindIndex] as? String {
obj = escapeIdentifier(str)
} else {
print("SwiftData Error -> During: Object Binding")
print(" -> Code: 203 - Object to bind as! identifier must be a String at array location: \(bindIndex)")
return ("", 203)
}
newSql = newSql.substringToIndex(newSql.endIndex.predecessor())
} else {
obj = escapeValue(objects[bindIndex])
}
newSql += obj
++bindIndex
} else {
newSql.append(char)
}
if char == "i" {
i = true
} else if i {
i = false
}
}
if bindIndex != objects.count {
print("SwiftData Error -> During: Object Binding")
print(" -> Code: 202 - Too many objects to bind provided")
return ("", 202)
}
return (newSql, nil)
}
//return escaped String value of AnyObject
func escapeValue(obj: AnyObject?) -> String {
if let obj: AnyObject = obj {
if obj is String {
return "'\(escapeStringValue(obj as! String))'"
}
if obj is Double || obj is Int {
return "\(obj)"
}
if obj is Bool {
if obj as! Bool {
return "1"
} else {
return "0"
}
}
if obj is NSData {
let str = "\(obj)"
var newStr = ""
for char in str.characters {
if char != "<" && char != ">" && char != " " {
newStr.append(char)
}
}
return "X'\(newStr)'"
}
if obj is NSDate {
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
return "\(escapeValue(dateFormatter.stringFromDate(obj as! NSDate)))"
}
if obj is UIImage {
if let imageID = SD.saveUIImage(obj as! UIImage) {
return "'\(escapeStringValue(imageID))'"
}
print("SwiftData Warning -> Cannot save image, NULL will be inserted into the database")
return "NULL"
}
print("SwiftData Warning -> Object \"\(obj)\" is not a supported type and will be inserted into the database as! NULL")
return "NULL"
} else {
return "NULL"
}
}
//return escaped String identifier
func escapeIdentifier(obj: String) -> String {
return "\"\(escapeStringIdentifier(obj))\""
}
//escape string
func escapeStringValue(str: String) -> String {
var escapedStr = ""
for char in str.characters {
if char == "'" {
escapedStr += "'"
}
escapedStr.append(char)
}
return escapedStr
}
//escape string
func escapeStringIdentifier(str: String) -> String {
var escapedStr = ""
for char in str.characters {
if char == "\"" {
escapedStr += "\""
}
escapedStr.append(char)
}
return escapedStr
}
}
// MARK: - SQL Creation Functions
extension SwiftData {
/**
Column Data Types
:param: StringVal A column with type String, corresponds to SQLite type "TEXT"
:param: IntVal A column with type Int, corresponds to SQLite type "INTEGER"
:param: DoubleVal A column with type Double, corresponds to SQLite type "DOUBLE"
:param: BoolVal A column with type Bool, corresponds to SQLite type "BOOLEAN"
:param: DataVal A column with type NSdata, corresponds to SQLite type "BLOB"
:param: DateVal A column with type NSDate, corresponds to SQLite type "DATE"
:param: UIImageVal A column with type String (the path value of saved UIImage), corresponds to SQLite type "TEXT"
*/
public enum DataType {
case StringVal
case IntVal
case DoubleVal
case BoolVal
case DataVal
case DateVal
case UIImageVal
private func toSQL() -> String {
switch self {
case .StringVal, .UIImageVal:
return "TEXT"
case .IntVal:
return "INTEGER"
case .DoubleVal:
return "DOUBLE"
case .BoolVal:
return "BOOLEAN"
case .DataVal:
return "BLOB"
case .DateVal:
return "DATE"
}
}
}
/**
Flags for custom connection to the SQLite database
:param: ReadOnly Opens the SQLite database with the flag "SQLITE_OPEN_READONLY"
:param: ReadWrite Opens the SQLite database with the flag "SQLITE_OPEN_READWRITE"
:param: ReadWriteCreate Opens the SQLite database with the flag "SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE"
*/
public enum Flags {
case ReadOnly
case ReadWrite
case ReadWriteCreate
private func toSQL() -> Int32 {
switch self {
case .ReadOnly:
return SQLITE_OPEN_READONLY
case .ReadWrite:
return SQLITE_OPEN_READWRITE
case .ReadWriteCreate:
return SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
}
}
}
}
extension SwiftData.SQLiteDB {
//create a table
func createSQLTable(table: String, withColumnsAndTypes values: [String: SwiftData.DataType]) -> Int? {
var sqlStr = "CREATE TABLE \(table) (ID INTEGER PRIMARY KEY AUTOINCREMENT, "
var firstRun = true
for value in values {
if firstRun {
sqlStr += "\(escapeIdentifier(value.0)) \(value.1.toSQL())"
firstRun = false
} else {
sqlStr += ", \(escapeIdentifier(value.0)) \(value.1.toSQL())"
}
}
sqlStr += ")"
return executeChange(sqlStr)
}
//delete a table
func deleteSQLTable(table: String) -> Int? {
let sqlStr = "DROP TABLE \(table)"
return executeChange(sqlStr)
}
//get existing table names
func existingTables() -> (result: [String], error: Int?) {
let sqlStr = "SELECT name FROM sqlite_master WHERE type = 'table'"
var tableArr = [String]()
let results = executeQuery(sqlStr)
if let err = results.error {
return (tableArr, err)
}
for row in results.result {
if let table = row["name"]?.asString() {
tableArr.append(table)
} else {
print("SwiftData Error -> During: Finding Existing Tables")
print(" -> Code: 403 - Error extracting table names from sqlite_master")
return (tableArr, 403)
}
}
return (tableArr, nil)
}
//create an index
func createIndex(name: String, columns: [String], table: String, unique: Bool) -> Int? {
if columns.count < 1 {
print("SwiftData Error -> During: Creating Index")
print(" -> Code: 401 - At least one column name must be provided")
return 401
}
var sqlStr = ""
if unique {
sqlStr = "CREATE UNIQUE INDEX \(name) ON \(table) ("
} else {
sqlStr = "CREATE INDEX \(name) ON \(table) ("
}
var firstRun = true
for column in columns {
if firstRun {
sqlStr += column
firstRun = false
} else {
sqlStr += ", \(column)"
}
}
sqlStr += ")"
return executeChange(sqlStr)
}
//remove an index
func removeIndex(name: String) -> Int? {
let sqlStr = "DROP INDEX \(name)"
return executeChange(sqlStr)
}
//obtain list of existing indexes
func existingIndexes() -> (result: [String], error: Int?) {
let sqlStr = "SELECT name FROM sqlite_master WHERE type = 'index'"
var indexArr = [String]()
let results = executeQuery(sqlStr)
if let err = results.error {
return (indexArr, err)
}
for res in results.result {
if let index = res["name"]?.asString() {
indexArr.append(index)
} else {
print("SwiftData Error -> During: Finding Existing Indexes")
print(" -> Code: 402 - Error extracting index names from sqlite_master")
print("Error finding existing indexes -> Error extracting index names from sqlite_master")
return (indexArr, 402)
}
}
return (indexArr, nil)
}
//obtain list of existing indexes for a specific table
func existingIndexesForTable(table: String) -> (result: [String], error: Int?) {
let sqlStr = "SELECT name FROM sqlite_master WHERE type = 'index' AND tbl_name = '\(table)'"
var indexArr = [String]()
let results = executeQuery(sqlStr)
if let err = results.error {
return (indexArr, err)
}
for res in results.result {
if let index = res["name"]?.asString() {
indexArr.append(index)
} else {
print("SwiftData Error -> During: Finding Existing Indexes for a Table")
print(" -> Code: 402 - Error extracting index names from sqlite_master")
return (indexArr, 402)
}
}
return (indexArr, nil)
}
}
// MARK: - SDError Functions
extension SwiftData.SDError {
//get the error message from the error code
private static func errorMessageFromCode(errorCode: Int) -> String {
switch errorCode {
//no error
case -1:
return "No error"
//SQLite error codes and descriptions as! per: http://www.sqlite.org/c3ref/c_abort.html
case 0:
return "Successful result"
case 1:
return "SQL error or missing database"
case 2:
return "Internal logic error in SQLite"
case 3:
return "Access permission denied"
case 4:
return "Callback routine requested an abort"
case 5:
return "The database file is locked"
case 6:
return "A table in the database is locked"
case 7:
return "A malloc() failed"
case 8:
return "Attempt to write a readonly database"
case 9:
return "Operation terminated by sqlite3_interrupt()"
case 10:
return "Some kind of disk I/O error occurred"
case 11:
return "The database disk image is malformed"
case 12:
return "Unknown opcode in sqlite3_file_control()"
case 13:
return "Insertion failed because database is full"
case 14:
return "Unable to open the database file"
case 15:
return "Database lock protocol error"
case 16:
return "Database is empty"
case 17:
return "The database schema changed"
case 18:
return "String or BLOB exceeds size limit"
case 19:
return "Abort due to constraint violation"
case 20:
return "Data type mismatch"
case 21:
return "Library used incorrectly"
case 22:
return "Uses OS features not supported on host"
case 23:
return "Authorization denied"
case 24:
return "Auxiliary database format error"
case 25:
return "2nd parameter to sqlite3_bind out of range"
case 26:
return "File opened that is not a database file"
case 27:
return "Notifications from sqlite3_log()"
case 28:
return "Warnings from sqlite3_log()"
case 100:
return "sqlite3_step() has another row ready"
case 101:
return "sqlite3_step() has finished executing"
//custom SwiftData errors
//->binding errors
case 201:
return "Not enough objects to bind provided"
case 202:
return "Too many objects to bind provided"
case 203:
return "Object to bind as! identifier must be a String"
//->custom connection errors
case 301:
return "A custom connection is already open"
case 302:
return "Cannot open a custom connection inside a transaction"
case 303:
return "Cannot open a custom connection inside a savepoint"
case 304:
return "A custom connection is not currently open"
case 305:
return "Cannot close a custom connection inside a transaction"
case 306:
return "Cannot close a custom connection inside a savepoint"
//->index and table errors
case 401:
return "At least one column name must be provided"
case 402:
return "Error extracting index names from sqlite_master"
case 403:
return "Error extracting table names from sqlite_master"
//->transaction and savepoint errors
case 501:
return "Cannot begin a transaction within a savepoint"
case 502:
return "Cannot begin a transaction within another transaction"
//unknown error
default:
//what the fuck happened?!?
return "Unknown error"
}
}
}
public typealias SD = SwiftData
| mit | 167c65d0efef47dcd965859c58db4f0b | 35.652859 | 273 | 0.542333 | 5.220893 | false | false | false | false |
Zewo/HTTP | Sources/HTTP/Message/Request.swift | 5 | 6691 | import Axis
public struct Request : Message {
public enum Method {
case delete
case get
case head
case post
case put
case connect
case options
case trace
case patch
case other(method: String)
}
public var method: Method
public var url: URL
public var version: Version
public var headers: Headers
public var body: Body
public var storage: [String: Any]
public init(method: Method, url: URL, version: Version, headers: Headers, body: Body) {
self.method = method
self.url = url
self.version = version
self.headers = headers
self.body = body
self.storage = [:]
}
}
public protocol RequestInitializable {
init(request: Request)
}
public protocol RequestRepresentable {
var request: Request { get }
}
public protocol RequestConvertible : RequestInitializable, RequestRepresentable {}
extension Request : RequestConvertible {
public init(request: Request) {
self = request
}
public var request: Request {
return self
}
}
extension Request {
public init(method: Method = .get, url: URL = URL(string: "/")!, headers: Headers = [:], body: Body) {
self.init(
method: method,
url: url,
version: Version(major: 1, minor: 1),
headers: headers,
body: body
)
switch body {
case let .buffer(body):
self.headers["Content-Length"] = body.count.description
default:
self.headers["Transfer-Encoding"] = "chunked"
}
}
public init(method: Method = .get, url: URL = URL(string: "/")!, headers: Headers = [:], body: BufferRepresentable = Buffer()) {
self.init(
method: method,
url: url,
headers: headers,
body: .buffer(body.buffer)
)
}
public init(method: Method = .get, url: URL = URL(string: "/")!, headers: Headers = [:], body: InputStream) {
self.init(
method: method,
url: url,
headers: headers,
body: .reader(body)
)
}
public init(method: Method = .get, url: URL = URL(string: "/")!, headers: Headers = [:], body: @escaping (OutputStream) throws -> Void) {
self.init(
method: method,
url: url,
headers: headers,
body: .writer(body)
)
}
}
extension Request {
public init?(method: Method = .get, url: String, headers: Headers = [:], body: BufferRepresentable = Buffer()) {
guard let url = URL(string: url) else {
return nil
}
self.init(
method: method,
url: url,
headers: headers,
body: body
)
}
public init?(method: Method = .get, url: String, headers: Headers = [:], body: InputStream) {
guard let url = URL(string: url) else {
return nil
}
self.init(
method: method,
url: url,
headers: headers,
body: body
)
}
public init?(method: Method = .get, url: String, headers: Headers = [:], body: @escaping (OutputStream) throws -> Void) {
guard let url = URL(string: url) else {
return nil
}
self.init(
method: method,
url: url,
headers: headers,
body: body
)
}
}
extension Request {
public var path: String? {
return url.path
}
public var queryItems: [URLQueryItem] {
return url.queryItems
}
}
extension Request {
public var accept: [MediaType] {
get {
var acceptedMediaTypes: [MediaType] = []
if let acceptString = headers["Accept"] {
let acceptedTypesString = acceptString.split(separator: ",")
for acceptedTypeString in acceptedTypesString {
let acceptedTypeTokens = acceptedTypeString.split(separator: ";")
if acceptedTypeTokens.count >= 1 {
let mediaTypeString = acceptedTypeTokens[0].trim()
if let acceptedMediaType = try? MediaType(string: mediaTypeString) {
acceptedMediaTypes.append(acceptedMediaType)
}
}
}
}
return acceptedMediaTypes
}
set(accept) {
headers["Accept"] = accept.map({$0.type + "/" + $0.subtype}).joined(separator: ", ")
}
}
public var cookies: Set<Cookie> {
get {
return headers["Cookie"].flatMap({Set<Cookie>(cookieHeader: $0)}) ?? []
}
set(cookies) {
headers["Cookie"] = cookies.map({$0.description}).joined(separator: ", ")
}
}
public var authorization: String? {
get {
return headers["Authorization"]
}
set(authorization) {
headers["Authorization"] = authorization
}
}
public var host: String? {
get {
return headers["Host"]
}
set(host) {
headers["Host"] = host
}
}
public var userAgent: String? {
get {
return headers["User-Agent"]
}
set(userAgent) {
headers["User-Agent"] = userAgent
}
}
}
extension Request {
public typealias UpgradeConnection = (Response, Stream) throws -> Void
public var upgradeConnection: UpgradeConnection? {
return storage["request-connection-upgrade"] as? UpgradeConnection
}
public mutating func upgradeConnection(_ upgrade: @escaping UpgradeConnection) {
storage["request-connection-upgrade"] = upgrade
}
}
extension Request {
public var pathParameters: [String: String] {
get {
return storage["pathParameters"] as? [String: String] ?? [:]
}
set(pathParameters) {
storage["pathParameters"] = pathParameters
}
}
}
extension Request : CustomStringConvertible {
public var requestLineDescription: String {
return String(describing: method) + " " + url.absoluteString + " HTTP/" + String(describing: version.major) + "." + String(describing: version.minor) + "\n"
}
public var description: String {
return requestLineDescription +
headers.description
}
}
extension Request : CustomDebugStringConvertible {
public var debugDescription: String {
return description + "\n" + storageDescription
}
}
| mit | 20ef897ff50560e2f48768894445ba90 | 24.833977 | 164 | 0.543267 | 4.685574 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/Core/APIClient_ObjC.swift | 1 | 32353 | //
// CreatubblesAPIClient_ObjC.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
extension APIClient {
// MARK: - Session
public func _login(_ username: String, password: String, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return login(username: username, password: password) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
public func _authenticate(completion: ((NSError?) -> (Void))?) -> RequestHandler {
return authenticate {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
public func _logout() {
logout()
}
public func _isLoggedIn() -> Bool {
return isLoggedIn()
}
public func _getLandingURL(_ type: LandingURLType, completion: ((Array<LandingURL>?, NSError?) -> (Void))?) -> RequestHandler {
return getLandingURL(type: type) {
(landingUrls, error) -> (Void) in
completion?(landingUrls, APIClient.errorTypeToNSError(error))
}
}
public func _getLandingURLForCreation(_ creationId: String, completion: ((Array<LandingURL>?, NSError?) -> (Void))?) -> RequestHandler {
return getLandingURL(creationId: creationId) {
(landingUrls, error) -> (Void) in
completion?(landingUrls, APIClient.errorTypeToNSError(error))
}
}
// MARK: - Users handling
public func _getUser(_ userId: String, completion: ((User?, NSError?) -> (Void))?) -> RequestHandler {
return getUser(userId: userId) {
(user, error) -> (Void) in
completion?(user, APIClient.errorTypeToNSError(error))
}
}
public func _getCurrentUser(_ completion: ((User?, NSError?) -> (Void))?) -> RequestHandler {
return getCurrentUser {
(user, error) -> (Void) in
completion?(user, APIClient.errorTypeToNSError(error))
}
}
public func _switchUser(targetUserId: String, accessToken: String, completion: ((String?, NSError?) -> (Void))?) -> RequestHandler {
return switchUser(targetUserId: targetUserId, accessToken: accessToken) {
(accessToken, error) -> (Void) in
completion?(accessToken, APIClient.errorTypeToNSError(error))
}
}
public func _reportUser(userId: String, message: String, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return reportUser(userId: userId, message: message) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
public func _getCreators(userId: String?, query: String?, pagingData: PagingData?, completion: ((Array<User>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getCreators(userId: userId, query: query, pagingData: pagingData) {
(users, pInfo, error) -> (Void) in
completion?(users, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _getCreators(groupId: String, pagingData: PagingData?, completion: ((Array<User>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getCreators(groupId: groupId, pagingData: pagingData) {
(users, pInfo, error) -> (Void) in
completion?(users, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _getSwitchUsers(query: String?, pagingData: PagingData?, completion: ((Array<User>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getSwitchUsers(query: query, pagingData: pagingData) {
(users, pInfo, error) -> (Void) in
completion?(users, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _getManagers(_ userId: String?, query: String?, pagingData: PagingData?, completion: ((Array<User>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getManagers(userId: userId, query: query, pagingData: pagingData) {
(users, pInfo, error) -> (Void) in
completion?(users, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _newCreator(_ creatorData: NewCreatorData, completion: ((User?, NSError?) -> (Void))?) -> RequestHandler {
return newCreator(data: creatorData) {
(user, error) -> (Void) in
completion?(user, APIClient.errorTypeToNSError(error))
}
}
public func _getGroupCreatorsInBatchMode(groupId: String, completion: ((Array<User>?, NSError?) -> (Void))?) -> RequestHandler {
return getGroupCreatorsInBatchMode(groupId: groupId) {
(users, error) -> (Void) in
completion?(users, APIClient.errorTypeToNSError(error))
}
}
public func _editProfile(identifier: String, data: EditProfileData, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return editProfile(userId: identifier, data: data) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
public func _createMultipleCreators(data: CreateMultipleCreatorsData, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return createMultipleCreators(data: data) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
public func _getMyConnections(query: String?, pagingData: PagingData?, completion: ((Array<User>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getMyConnections(query: query, pagingData: pagingData) {
(users, pInfo, error) -> (Void) in
completion?(users, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _getOtherUsersMyConnections(userId: String, query: String?, pagingData: PagingData?, completion: ((Array<User>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getOtherUsersMyConnections(userId: userId, query:query, pagingData: pagingData) {
(users, pInfo, error) -> (Void) in
completion?(users, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _getUsersFollowedByAUser(userId: String, pagingData: PagingData?, completion: ((Array<User>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getUsersFollowedByAUser(userId: userId, pagingData: pagingData) {
(users, pInfo, error) -> (Void) in
completion?(users, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _getUserAccountData(userId: String, completion: ((UserAccountDetails?, NSError?) -> (Void))?) -> RequestHandler {
return getUserAccountData(userId: userId) {
(userAccountDetails, error) -> (Void) in
completion?(userAccountDetails, APIClient.errorTypeToNSError(error))
}
}
// MARK: - Gallery handling
public func _getGallery(_ galleryId: String, completion: ((Gallery?, NSError?) -> (Void))?) -> RequestHandler {
return getGallery(galleryId: galleryId) {
(gallery, error) -> (Void) in
completion?(gallery, APIClient.errorTypeToNSError(error))
}
}
public func _newGallery(_ galleryData: NewGalleryData, completion: ((Gallery?, NSError?) -> (Void))?) -> RequestHandler {
return newGallery(data: galleryData) {
(gallery, error) -> (Void) in
completion?(gallery, APIClient.errorTypeToNSError(error))
}
}
public func _getGalleries(_ userId: String?, query: String?, pagingData: PagingData?, sort: SortOrder, filter: GalleriesRequestFilter?, completion: ((Array<Gallery>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getGalleries(userId: userId, query:query, pagingData: pagingData, sort: sort, filter: filter) {
(galleries, pInfo, error) -> (Void) in
completion?(galleries, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _getGalleries(creationId: String, pagingData: PagingData?, sort: SortOrder?, filter: GalleriesRequestFilter?, completion: ((Array<Gallery>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getGalleries(creationId: creationId, pagingData: pagingData, sort: sort, filter: filter) {
(galleries, pInfo, error) -> (Void) in
completion?(galleries, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _getMyGalleries(pagingData: PagingData?, completion: ((Array<Gallery>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getMyGalleries(pagingData) {
(galleries, pInfo, error) -> (Void) in
completion?(galleries, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _getMyOwnedGalleries(pagingData: PagingData?, completion: ((Array<Gallery>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getMyOwnedGalleries(pagingData) {
(galleries, pInfo, error) -> (Void) in
completion?(galleries, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _getMySharedGalleries(pagingData: PagingData?, completion: ((Array<Gallery>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getMySharedGalleries(pagingData) {
(galleries, pInfo, error) -> (Void) in
completion?(galleries, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _getMyFavoriteGalleries(pagingData: PagingData?, completion: ((Array<Gallery>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getMyFavoriteGalleries(pagingData) {
(galleries, pInfo, error) -> (Void) in
completion?(galleries, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _getFeaturedGalleries(pagingData: PagingData?, completion: ((Array<Gallery>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getFeaturedGalleries(pagingData) {
(galleries, pInfo, error) -> (Void) in
completion?(galleries, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _getMyGalleriesInBatchMode(completion: ((Array<Gallery>?, NSError?) -> (Void))?) -> RequestHandler {
return getMyGalleriesInBatchMode {
(galleries, error) -> (Void) in
completion?(galleries, APIClient.errorTypeToNSError(error))
}
}
public func _getOwnedGalleriesInBatchMode(completion: ((Array<Gallery>?, NSError?) -> (Void))?) -> RequestHandler {
return getOwnedGalleriesInBatchMode {
(galleries, error) -> (Void) in
completion?(galleries, APIClient.errorTypeToNSError(error))
}
}
public func _getSharedGalleriesInBatchMode(completion: ((Array<Gallery>?, NSError?) -> (Void))?) -> RequestHandler {
return getSharedGalleriesInBatchMode {
(galleries, error) -> (Void) in
completion?(galleries, APIClient.errorTypeToNSError(error))
}
}
public func _getFavoriteGalleriesInBatchMode(completion: ((Array<Gallery>?, NSError?) -> (Void))?) -> RequestHandler {
return getFavoriteGalleriesInBatchMode {
(galleries, error) -> (Void) in
completion?(galleries, APIClient.errorTypeToNSError(error))
}
}
public func _getFeaturedGalleriesInBatchMode(completion: ((Array<Gallery>?, NSError?) -> (Void))?) -> RequestHandler {
return getFeaturedGalleriesInBatchMode {
(galleries, error) -> (Void) in
completion?(galleries, APIClient.errorTypeToNSError(error))
}
}
public func _updateGallery(data: UpdateGalleryData, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return updateGallery(data: data) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
public func _reportGallery(galleryId: String, message: String, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return reportGallery(galleryId: galleryId, message: message) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
public func _submitCreationToGallery(galleryId: String, creationId: String, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return submitCreationToGallery(galleryId: galleryId, creationId: creationId) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
// MARK: - Creation handling
public func _getCreation(_ creationId: String, completion: ((Creation?, NSError?) -> (Void))?) -> RequestHandler {
return getCreation(creationId: creationId) {
(creation, error) -> (Void) in
completion?(creation, APIClient.errorTypeToNSError(error))
}
}
public func _getCreations(_ galleryId: String, userId: String?, keyword: String?, pagingData: PagingData?, sortOrder: SortOrder, partnerApplicationId: String?, onlyPublic: Bool, completion: ((Array<Creation>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getCreations(galleryId: galleryId, userId: userId, keyword: keyword, pagingData: pagingData, sortOrder: sortOrder, partnerApplicationId: partnerApplicationId, onlyPublic: onlyPublic) {
(creations, pInfo, error) -> (Void) in
completion?(creations, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _newCreation(_ creationData: NewCreationData, localDataPreparationCompletion: ((NSError?) -> (Void))?, completion: ((Creation?, NSError?) -> (Void))?) -> CreationUploadSessionPublicData? {
return newCreation(data: creationData, localDataPreparationCompletion: {
(error) -> (Void) in
localDataPreparationCompletion?(APIClient.errorTypeToNSError(error))
}, completion: { (creation, error) -> (Void) in
completion?(creation, APIClient.errorTypeToNSError(error))
})
}
public func _reportCreation(creationId: String, message: String, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return reportCreation(creationId: creationId, message: message) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
public func _getRecommendedCreationsByUser(userId: String, pagingData: PagingData?, completion: ((Array<Creation>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getRecomendedCreationsByUser(userId: userId, pagingData: pagingData) {
(creations, pInfo, error) -> (Void) in
completion?(creations, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _getRecommendedCreationsByCreation(creationId: String, pagingData: PagingData?, completion: ((Array<Creation>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getRecomendedCreationsByCreation(creationId: creationId, pagingData: pagingData) {
(creations, pInfo, error) -> (Void) in
completion?(creations, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _editCreation(creationId: String, data: EditCreationData, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return editCreation(creationId: creationId, data: data) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
public func _removeCreation(creationId: String, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return removeCreation(creationId: creationId) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
// MARK: - Batch fetching
public func _getCreationsInBatchMode(_ galleryId: String?, userId: String?, keyword: String?, partnerApplicationId: String?, sortOrder: SortOrder, onlyPublic: Bool, completion: ((Array<Creation>?, NSError?) -> (Void))?) -> RequestHandler {
return getCreationsInBatchMode(galleryId: galleryId, userId: userId, keyword: keyword, partnerApplicationId: partnerApplicationId, sortOrder: sortOrder, onlyPublic: onlyPublic) {
(creations, error) -> (Void) in
completion?(creations, APIClient.errorTypeToNSError(error))
}
}
public func _getGalleriesInBatchMode(_ userId: String?, query: String?, sort: SortOrder, filter: GalleriesRequestFilter?, completion: ((Array<Gallery>?, NSError?) -> (Void))?) -> RequestHandler {
return getGalleriesInBatchMode(userId: userId, query:query, sort: sort, filter: filter) {
(galleries, error) -> (Void) in
completion?(galleries, APIClient.errorTypeToNSError(error))
}
}
public func _getCreatorsInBatchMode(_ userId: String?, query: String?, completion: ((Array<User>?, NSError?) -> (Void))?) -> RequestHandler {
return getCreatorsInBatchMode(userId: userId, query: query) {
(users, error) -> (Void) in
completion?(users, APIClient.errorTypeToNSError(error))
}
}
public func _getManagersInBatchMode(_ userId: String?, query: String?, completion: ((Array<User>?, NSError?) -> (Void))?) -> RequestHandler {
return getManagersInBatchMode(userId: userId, query: query) {
(users, error) -> (Void) in
completion?(users, APIClient.errorTypeToNSError(error))
}
}
// MARK: - Upload Sessions
public func _getAllActiveUploadSessionPublicData() -> Array<CreationUploadSessionPublicData> {
return getAllActiveUploadSessionPublicData()
}
public func _getAllFinishedUploadSessionPublicData() -> Array<CreationUploadSessionPublicData> {
return getAllFinishedUploadSessionPublicData()
}
public func _startAllNotFinishedUploadSessions(_ completion: ((Creation?, NSError?) -> (Void))?) {
startAllNotFinishedUploadSessions {
(creation, error) -> (Void) in
completion?(creation, APIClient.errorTypeToNSError(error))
}
}
// MARK: - Bubbles
public func _getBubblesForCreationWithIdentifier(_ identifier: String, pagingData: PagingData?, completion: ((Array<Bubble>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getBubbles(creationId: identifier, pagingData: pagingData) {
(bubbles, pInfo, error) -> (Void) in
completion?(bubbles, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _getBubblesForUserWithIdentifier(_ identifier: String, pagingData: PagingData?, completion: ((Array<Bubble>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getBubbles(userId: identifier, pagingData: pagingData) {
(bubbles, pInfo, error) -> (Void) in
completion?(bubbles, pInfo, APIClient.errorTypeToNSError(error as Error?))
}
}
public func _getBubblesForGalleryWithIdentifier(_ identifier: String, pagingData: PagingData?, completion: ((Array<Bubble>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getBubbles(galleryId: identifier, pagingData: pagingData) {
(bubbles, pInfo, error) -> (Void) in
completion?(bubbles, pInfo, APIClient.errorTypeToNSError(error as Error?))
}
}
public func _newBubble(_ data: NewBubbleData, completion: ((Bubble?, NSError?) -> (Void))?) -> RequestHandler {
return newBubble(data: data) {
(bubble, error) -> (Void) in
completion?(bubble, APIClient.errorTypeToNSError(error))
}
}
public func _updateBubble(data: UpdateBubbleData, completion: ((Bubble?, NSError?) -> (Void))?) -> RequestHandler {
return updateBubble(data: data) {
(bubble, error) -> (Void) in
completion?(bubble, APIClient.errorTypeToNSError(error))
}
}
public func _deleteBubble(bubbleId: String, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return deleteBubble(bubbleId: bubbleId) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
// MARK: - Toyboo Creation
public func _getToybooCreation(creationId: String, completion: ((ToybooCreation?, NSError?) -> (Void))?) -> RequestHandler {
return getToybooCreation(creationId: creationId) {
(toybooCreation, error) -> (Void) in
completion?(toybooCreation, APIClient.errorTypeToNSError(error) )
}
}
// MARK: - Groups
public func _fetchGroup(groupId: String, completion: ((Group?, NSError?) -> (Void))?) -> RequestHandler {
return fetchGroup(groupId: groupId) {
(group, error) -> (Void) in
completion?(group, APIClient.errorTypeToNSError(error))
}
}
public func _fetchGroups(completion: ((Array<Group>?, NSError?) -> (Void))?) -> RequestHandler {
return fetchGroups {
(groups, errors) -> (Void) in
completion?(groups, APIClient.errorTypeToNSError(errors))
}
}
public func _newGroup(data: NewGroupData, completion: ((Group?, NSError?) -> (Void))?) -> RequestHandler {
return newGroup(data: data) {
(group, error) -> (Void) in
completion?(group, APIClient.errorTypeToNSError(error))
}
}
public func _editGroup(groupId: String, data: EditGroupData, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return editGroup(groupId: groupId, data: data) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
public func _deleteGroup(groupId: String, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return deleteGroup(groupId: groupId) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
// MARK: - Comments
public func _addComment(data: NewCommentData, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return addComment(data: data) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
public func _addComment(commentId: String, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return declineComment(commentId: commentId) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
public func _reportComment(commentId: String, message: String, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return reportComment(commentId: commentId, message: message) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
public func _getComments(creationId: String, pagingData: PagingData?, completion: ((Array<Comment>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getComments(creationId: creationId, pagingData: pagingData) {
(comments, pInfo, error) -> (Void) in
completion?(comments, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _getComments(userId: String, pagingData: PagingData?, completion: ((Array<Comment>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getComments(userId: userId, pagingData: pagingData) {
(comments, pInfo, error) -> (Void) in
completion?(comments, pInfo, APIClient.errorTypeToNSError(error))
}
}
public func _getComments(galleryId: String, pagingData: PagingData?, completion: ((Array<Comment>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getComments(galleryId: galleryId, pagingData: pagingData) {
(comments, pInfo, error) -> (Void) in
completion?(comments, pInfo, APIClient.errorTypeToNSError(error))
}
}
// MARK: - Contents
public func _getTrendingContent(pagingData: PagingData?, completion: ((ResponseData<ContentEntry>) -> (Void))?) -> RequestHandler {
return getTrendingContent(pagingData: pagingData) {
(contentEntries) -> (Void) in
completion?(contentEntries)
}
}
public func _getRecentContent(pagingData: PagingData?, completion: ((ResponseData<ContentEntry>) -> (Void))?) -> RequestHandler {
return getRecentContent(pagingData: pagingData) {
(contentEntries) -> (Void) in
completion?(contentEntries)
}
}
public func _getBubbledContent(userId: String, pagingData: PagingData?, completion: ((ResponseData<ContentEntry>) -> (Void))?) -> RequestHandler {
return getBubbledContent(userId: userId, pagingData: pagingData) {
(contentEntries) -> (Void) in
completion?(contentEntries)
}
}
public func _getMyConnectionsContent(pagingData: PagingData?, completion: ((ResponseData<ContentEntry>) -> (Void))?) -> RequestHandler {
return getMyConnectionsContent(pagingData: pagingData) {
(contentEntries) -> (Void) in
completion?(contentEntries)
}
}
public func _getContentsByUser(userId: String, pagingData: PagingData?, completion: ((ResponseData<ContentEntry>) -> (Void))?) -> RequestHandler {
return getContentsByAUser(userId: userId, pagingData: pagingData) {
(contentEntries) -> (Void) in
completion?(contentEntries)
}
}
public func _getFollowedContents(pagingData: PagingData?, completion: ((ResponseData<ContentEntry>) -> (Void))?) -> RequestHandler {
return getFollowedContents(pagingData) {
(contentEntries) -> (Void) in
completion?(contentEntries)
}
}
public func _getSearchedContents(query: String, pagingData: PagingData?, completion: ((ResponseData<ContentEntry>) -> (Void))?) -> RequestHandler {
return getSearchedContents(query: query, pagingData: pagingData) {
(contentEntries) -> (Void) in
completion?(contentEntries)
}
}
//Mark: - Custom Style
public func _fetchCustomStyleForUser(userId: String, completion: ((CustomStyle?, NSError?) -> (Void))?) -> RequestHandler {
return fetchCustomStyleForUser(userId: userId) {
(customStyle, error) -> (Void) in
completion?(customStyle, APIClient.errorTypeToNSError(error))
}
}
public func _editCustomStyleForUser(userId: String, data: CustomStyleEditData, completion: ((CustomStyle?, NSError?) -> (Void))?) -> RequestHandler {
return editCustomStyleForUser(userId: userId, withData: data) {
(customStyle, error) -> (Void) in
completion?(customStyle, APIClient.errorTypeToNSError(error))
}
}
// MARK: - Activities
public func _getActivities(pagingData: PagingData?, completion: ((Array<Activity>?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getActivities(pagingData: pagingData) {
(activities, pInfo, error) -> (Void) in
completion?(activities, pInfo, APIClient.errorTypeToNSError(error))
}
}
// MARK: - Notifications
public func _getNotifications(pagingdata: PagingData?, completion: ((Array<Notification>?, Array<Notification>?, _ newNotificationsCount: Int?, _ unreadNotificationsCount: Int?, _ hasUnreadNotifications: Bool?, PagingInfo?, NSError?) -> (Void))?) -> RequestHandler {
return getNotifications(pagingData: pagingdata) {
(responseData: ResponseData<Notification>?, newNotificationsCount: Int?, unreadNotificationsCount: Int?, hasUnreadNotifications: Bool?) -> (Void) in
completion?(responseData?.objects, responseData?.rejectedObjects, newNotificationsCount, unreadNotificationsCount, hasUnreadNotifications, responseData?.pagingInfo, APIClient.errorTypeToNSError(responseData?.error))
}
}
public func _markNotificationAsRead(notificationId: String, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return markNotificationAsRead(notificationId: notificationId) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
public func _trackWhenNotificationsWereViewed(completion: ((NSError?) -> (Void))?) -> RequestHandler {
return trackWhenNotificationsWereViewed {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
// MARK: - User Followings
public func _createUserFollowing(userId: String, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return createUserFollowing(userId: userId) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
public func _deleteUserFollowing(userId: String, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return deleteAUserFollowing(userId: userId) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
// MARK: - Partner Applications
public func _getPartnerApplication(id: String, completion: ((PartnerApplication?, NSError?) -> (Void))?) -> RequestHandler {
return getPartnerApplication(id) {
(partnerApplication, error) -> (Void) in
completion?(partnerApplication, APIClient.errorTypeToNSError(error))
}
}
public func _searchPartnerApplications(query: String, completion: ((Array<PartnerApplication>?, NSError?) -> (Void))?) -> RequestHandler {
return searchPartnerApplications(query) {
(partnerApplications, error) -> (Void) in
completion?(partnerApplications, APIClient.errorTypeToNSError(error))
}
}
// MARK: - Avatar
public func _getSuggestedAvatars(completion: ((Array<AvatarSuggestion>?, NSError?) -> (Void))?) -> RequestHandler {
return getSuggestedAvatars {
(suggestedAvatars, error) -> (Void) in
completion?(suggestedAvatars, APIClient.errorTypeToNSError(error))
}
}
public func _updateUserAvatar(userId: String, data: UpdateAvatarData, completion: ((NSError?) -> (Void))?) -> RequestHandler {
return updateUserAvatar(userId: userId, data: data) {
(error) -> (Void) in
completion?(APIClient.errorTypeToNSError(error))
}
}
// MARK: - Utils
static func errorTypeToNSError(_ error: Error?) -> NSError? {
if let error = error as? APIClientError {
let userInfo = [NSLocalizedDescriptionKey: error.title]
return NSError(domain: APIClientError.DefaultDomain, code: error.status, userInfo: userInfo)
}
if let error = error as NSError? {
return error
}
if let _ = error {
let userInfo = [NSLocalizedDescriptionKey: String(describing: error)]
return NSError(domain: APIClientError.DefaultDomain, code: APIClientError.UnknownStatus, userInfo: userInfo)
}
return nil
}
}
| mit | 383dfd474c22761da30a4e95e24b9090 | 46.230657 | 270 | 0.641826 | 4.550352 | false | false | false | false |
abonz/Swift | CoreImageCIDetector/CoreImageCIDetector/ViewController.swift | 6 | 5047 | //
// ViewController.swift
// CoreImageCIDetector
//
// Created by Carlos Butron on 07/12/14.
// Copyright (c) 2015 Carlos Butron. All rights reserved.
//
// 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
class ViewController: UIViewController {
var filePath: NSString = ""
var fileNameAndPath = NSURL()
var image = CIImage()
override func viewDidLoad() {
filePath = NSBundle.mainBundle().pathForResource("emotions", ofType: "jpg")!
fileNameAndPath = NSURL.fileURLWithPath(filePath as String)
image = CIImage(contentsOfURL:fileNameAndPath)!
let context = CIContext(options: nil)
let options = NSDictionary(object: CIDetectorAccuracyHigh, forKey: CIDetectorAccuracy)
let detector = CIDetector(ofType: CIDetectorTypeFace, context: context, options: options as? [String : AnyObject] )
let features: NSArray = detector.featuresInImage(image, options: [CIDetectorSmile:true,CIDetectorEyeBlink:true])
let imageView = UIImageView(image: UIImage(named: "emotions.jpg"))
self.view.addSubview(imageView)
//auxiliar view to invert.
let vistAux = UIView(frame: imageView.frame)
for faceFeature in features {
//Detection
let smile = faceFeature.hasSmile
let rightEyeBlinking = faceFeature.rightEyeClosed
let leftEyeBlinking = faceFeature.leftEyeClosed
//Face location
let faceRect = faceFeature.bounds
let faceView = UIView(frame: faceRect)
faceView.layer.borderWidth = 2
faceView.layer.borderColor = UIColor.redColor().CGColor
let faceWidth:CGFloat = faceRect.size.width
let faceHeight:CGFloat = faceRect.size.height
vistAux.addSubview(faceView)
//Smile location
if (smile==true) {
let smileView = UIView(frame: CGRectMake(faceFeature.mouthPosition.x-faceWidth*0.18, faceFeature.mouthPosition.y-faceHeight*0.1, faceWidth*0.4, faceHeight*0.2))
smileView.layer.cornerRadius = faceWidth*0.1
smileView.layer.borderWidth = 2
smileView.layer.borderColor = UIColor.greenColor().CGColor
smileView.layer.backgroundColor = UIColor.greenColor().CGColor
smileView.layer.opacity = 0.5
vistAux.addSubview(smileView)
}
//Right eye location
let rightEyeView = UIView(frame: CGRectMake(faceFeature.rightEyePosition.x-faceWidth*0.2, faceFeature.rightEyePosition.y-faceWidth*0.2, faceWidth*0.4, faceWidth*0.4))
rightEyeView.layer.cornerRadius = faceWidth*0.2
rightEyeView.layer.borderWidth = 2
rightEyeView.layer.borderColor = UIColor.redColor().CGColor
if (rightEyeBlinking==true){
rightEyeView.layer.backgroundColor = UIColor.yellowColor().CGColor
}else{
rightEyeView.layer.backgroundColor = UIColor.redColor().CGColor
}
rightEyeView.layer.opacity = 0.5
vistAux.addSubview(rightEyeView)
//Left eye location
let leftEyeView = UIView(frame: CGRectMake(faceFeature.leftEyePosition.x-faceWidth*0.2, faceFeature.leftEyePosition.y-faceWidth*0.2, faceWidth*0.4, faceWidth*0.4))
leftEyeView.layer.cornerRadius = faceWidth*0.2
leftEyeView.layer.borderWidth = 2
leftEyeView.layer.borderColor = UIColor.blueColor().CGColor
if (leftEyeBlinking==true){
leftEyeView.layer.backgroundColor = UIColor.yellowColor().CGColor
}else{
leftEyeView.layer.backgroundColor = UIColor.blueColor().CGColor
}
leftEyeView.layer.opacity = 0.5
vistAux.addSubview(leftEyeView)
}
self.view.addSubview(vistAux)
//Invert coords
vistAux.transform = CGAffineTransformMakeScale(1, -1)
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| gpl-3.0 | 53b88a10b686ad70fdae58f00cd2295c | 42.886957 | 178 | 0.63721 | 4.765817 | false | false | false | false |
rwebaz/Simple-Swift-OS | iOs8PlayGrounds/LyndaiOs8Loops.playground/section-1.swift | 1 | 1901 | // Lynda.com iOS 8 Loop functions by Simon Allardice
import UIKit
// Declare a variable and its type
var highScore:Int;
// Assign a value to the variable
highScore = 100;
// Change the value of the variable
highScore = highScore + 50;
/* Loop through 100 iterations of the variable
Incrementing the value of the variable by i each time */
for i in 0..<100 {
highScore = highScore + i;
}
// Present the current value of the variable to the screen
highScore;
// Surround all code blocks w curly braces ie.) { .... } in Swift Os
// Declare variables and constants
var balance = 5;
// balance = -4;
if balance < 0 {
println("The variable 'balance' is a negative value");
}
else
if balance > 0 {
println("The variable 'balance' is a positive value");
}
// 'for-in' loops w 'closed range operator
// Declare variables and constants
var total = 0;
for index in 1...100 {
total = total + index;
}
println("The total is \(total).")
/* Note: Remember to use '0...one unit less than the formal length of an array'
when looping through an array, as follows */
// 'for-in' loops w 'half-open range operator
for index in 0..<100 {} //where 100 = 'length of an array'
/* Note: 'for-in' loops can be used w strings, too */
// Declare variables and constants
var name = "Bob";
// name = "Stan";
for eachChar in name {
println(eachChar);
}
// While and Do-while loops
/* Note: In a Do-while loop the condition is evaluated AFTER the
function is executed at least once */
/* Whereas in a simple 'while' loop the condition is evaluated initially ...
And, then and only then if the condition is true does the function
fire-off */
while name == "Bob" {
println("The variable 'name' currently holds the string '\(name)'.");
break;
}
do {
println("The variable 'name' currently holds the string '\(name)'.")}
while name == "Stan"
| agpl-3.0 | 05564284a8eb9428c31ca08235fc316b | 17.104762 | 79 | 0.670174 | 3.620952 | false | false | false | false |
frootloops/swift | test/Serialization/Recovery/typedefs.swift | 1 | 17365 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-sil -o - -emit-module-path %t/Lib.swiftmodule -module-name Lib -I %S/Inputs/custom-modules -disable-objc-attr-requires-foundation-module %s | %FileCheck -check-prefix CHECK-VTABLE %s
// RUN: %target-swift-ide-test -source-filename=x -print-module -module-to-print Lib -I %t -I %S/Inputs/custom-modules | %FileCheck %s
// RUN: %target-swift-ide-test -source-filename=x -print-module -module-to-print Lib -I %t -I %S/Inputs/custom-modules -Xcc -DBAD > %t.txt
// RUN: %FileCheck -check-prefix CHECK-RECOVERY %s < %t.txt
// RUN: %FileCheck -check-prefix CHECK-RECOVERY-NEGATIVE %s < %t.txt
// RUN: %target-swift-frontend -typecheck -I %t -I %S/Inputs/custom-modules -Xcc -DBAD -DTEST -DVERIFY %s -verify
// RUN: %target-swift-frontend -emit-silgen -I %t -I %S/Inputs/custom-modules -Xcc -DBAD -DTEST %s | %FileCheck -check-prefix CHECK-SIL %s
// RUN: %target-swift-frontend -emit-ir -I %t -I %S/Inputs/custom-modules -DTEST %s | %FileCheck -check-prefix CHECK-IR %s
// RUN: %target-swift-frontend -emit-ir -I %t -I %S/Inputs/custom-modules -Xcc -DBAD -DTEST %s | %FileCheck -check-prefix CHECK-IR %s
#if TEST
import Typedefs
import Lib
// CHECK-SIL-LABEL: sil hidden @_T08typedefs11testSymbolsyyF
func testSymbols() {
// Check that the symbols are not using 'Bool'.
// CHECK-SIL: function_ref @_T03Lib1xs5Int32Vvau
_ = Lib.x
// CHECK-SIL: function_ref @_T03Lib9usesAssocs5Int32VSgvau
_ = Lib.usesAssoc
} // CHECK-SIL: end sil function '_T08typedefs11testSymbolsyyF'
// CHECK-IR-LABEL: define{{.*}} void @_T08typedefs18testVTableBuildingy3Lib4UserC4user_tF
public func testVTableBuilding(user: User) {
// The important thing in this CHECK line is the "i64 30", which is the offset
// for the vtable slot for 'lastMethod()'. If the layout here
// changes, please check that offset is still correct.
// CHECK-IR-NOT: ret
// CHECK-IR: getelementptr inbounds void (%T3Lib4UserC*)*, void (%T3Lib4UserC*)** %{{[0-9]+}}, {{i64 30|i32 33}}
_ = user.lastMethod()
} // CHECK-IR: ret void
#if VERIFY
let _: String = useAssoc(ImportedType.self) // expected-error {{cannot convert value of type 'Int32?' to specified type 'String'}}
let _: Bool? = useAssoc(ImportedType.self) // expected-error {{cannot convert value of type 'Int32?' to specified type 'Bool?'}}
let _: Int32? = useAssoc(ImportedType.self)
let _: String = useAssoc(AnotherType.self) // expected-error {{cannot convert value of type 'AnotherType.Assoc?' (aka 'Optional<Int32>') to specified type 'String'}}
let _: Bool? = useAssoc(AnotherType.self) // expected-error {{cannot convert value of type 'AnotherType.Assoc?' (aka 'Optional<Int32>') to specified type 'Bool?'}}
let _: Int32? = useAssoc(AnotherType.self)
let _ = wrapped // expected-error {{use of unresolved identifier 'wrapped'}}
let _ = unwrapped // okay
_ = usesWrapped(nil) // expected-error {{use of unresolved identifier 'usesWrapped'}}
_ = usesUnwrapped(nil) // expected-error {{nil is not compatible with expected argument type 'Int32'}}
let _: WrappedAlias = nil // expected-error {{use of undeclared type 'WrappedAlias'}}
let _: UnwrappedAlias = nil // expected-error {{nil cannot initialize specified type 'UnwrappedAlias' (aka 'Int32')}} expected-note {{add '?'}}
let _: ConstrainedWrapped<Int> = nil // expected-error {{use of undeclared type 'ConstrainedWrapped'}}
let _: ConstrainedUnwrapped<Int> = nil // expected-error {{type 'Int' does not conform to protocol 'HasAssoc'}}
func testExtensions(wrapped: WrappedInt, unwrapped: UnwrappedInt) {
wrapped.wrappedMethod() // expected-error {{value of type 'WrappedInt' (aka 'Int32') has no member 'wrappedMethod'}}
unwrapped.unwrappedMethod() // expected-error {{value of type 'UnwrappedInt' has no member 'unwrappedMethod'}}
***wrapped // This one works because of the UnwrappedInt extension.
***unwrapped // expected-error {{cannot convert value of type 'UnwrappedInt' to expected argument type 'Int32'}}
let _: WrappedProto = wrapped // expected-error {{value of type 'WrappedInt' (aka 'Int32') does not conform to specified type 'WrappedProto'}}
let _: UnwrappedProto = unwrapped // expected-error {{value of type 'UnwrappedInt' does not conform to specified type 'UnwrappedProto'}}
}
public class UserDynamicSub: UserDynamic {
override init() {}
}
// FIXME: Bad error message; really it's that the convenience init hasn't been
// inherited.
_ = UserDynamicSub(conveniently: 0) // expected-error {{argument passed to call that takes no arguments}}
public class UserDynamicConvenienceSub: UserDynamicConvenience {
override init() {}
}
_ = UserDynamicConvenienceSub(conveniently: 0)
public class UserSub : User {} // expected-error {{cannot inherit from class 'User' because it has overridable members that could not be loaded}}
#endif // VERIFY
#else // TEST
import Typedefs
prefix operator ***
// CHECK-LABEL: extension WrappedInt : WrappedProto {
// CHECK-NEXT: func wrappedMethod()
// CHECK-NEXT: prefix static func *** (x: WrappedInt)
// CHECK-NEXT: }
// CHECK-RECOVERY-NEGATIVE-NOT: extension WrappedInt
extension WrappedInt: WrappedProto {
public func wrappedMethod() {}
public static prefix func ***(x: WrappedInt) {}
}
// CHECK-LABEL: extension Int32 : UnwrappedProto {
// CHECK-NEXT: func unwrappedMethod()
// CHECK-NEXT: prefix static func *** (x: UnwrappedInt)
// CHECK-NEXT: }
// CHECK-RECOVERY-LABEL: extension Int32 : UnwrappedProto {
// CHECK-RECOVERY-NEXT: func unwrappedMethod()
// CHECK-RECOVERY-NEXT: prefix static func *** (x: Int32)
// CHECK-RECOVERY-NEXT: }
// CHECK-RECOVERY-NEGATIVE-NOT: extension UnwrappedInt
extension UnwrappedInt: UnwrappedProto {
public func unwrappedMethod() {}
public static prefix func ***(x: UnwrappedInt) {}
}
// CHECK-LABEL: class User {
// CHECK-RECOVERY-LABEL: class User {
open class User {
// CHECK: var unwrappedProp: UnwrappedInt?
// CHECK-RECOVERY: var unwrappedProp: Int32?
public var unwrappedProp: UnwrappedInt?
// CHECK: var wrappedProp: WrappedInt?
// CHECK-RECOVERY: /* placeholder for _ */
// CHECK-RECOVERY: /* placeholder for _ */
// CHECK-RECOVERY: /* placeholder for _ */
public var wrappedProp: WrappedInt?
// CHECK: func returnsUnwrappedMethod() -> UnwrappedInt
// CHECK-RECOVERY: func returnsUnwrappedMethod() -> Int32
public func returnsUnwrappedMethod() -> UnwrappedInt { fatalError() }
// CHECK: func returnsWrappedMethod() -> WrappedInt
// CHECK-RECOVERY: /* placeholder for returnsWrappedMethod() */
public func returnsWrappedMethod() -> WrappedInt { fatalError() }
// CHECK: func constrainedUnwrapped<T>(_: T) where T : HasAssoc, T.Assoc == UnwrappedInt
// CHECK-RECOVERY: func constrainedUnwrapped<T>(_: T) where T : HasAssoc, T.Assoc == Int32
public func constrainedUnwrapped<T: HasAssoc>(_: T) where T.Assoc == UnwrappedInt { fatalError() }
// CHECK: func constrainedWrapped<T>(_: T) where T : HasAssoc, T.Assoc == WrappedInt
// CHECK-RECOVERY: /* placeholder for constrainedWrapped(_:) */
public func constrainedWrapped<T: HasAssoc>(_: T) where T.Assoc == WrappedInt { fatalError() }
// CHECK: subscript(_: WrappedInt) -> () { get }
// CHECK-RECOVERY: /* placeholder for _ */
public subscript(_: WrappedInt) -> () { return () }
// CHECK: subscript<T>(_: T) -> () where T : HasAssoc, T.Assoc == WrappedInt { get }
// CHECK-RECOVERY: /* placeholder for _ */
public subscript<T: HasAssoc>(_: T) -> () where T.Assoc == WrappedInt { return () }
// CHECK: init()
// CHECK-RECOVERY: init()
public init() {}
// CHECK: init(wrapped: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
public init(wrapped: WrappedInt) {}
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
public convenience init(conveniently: Int) { self.init() }
// CHECK: convenience init<T>(generic: T) where T : HasAssoc, T.Assoc == WrappedInt
// CHECK-RECOVERY: /* placeholder for init(generic:) */
public convenience init<T: HasAssoc>(generic: T) where T.Assoc == WrappedInt { self.init() }
// CHECK: required init(wrappedRequired: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequired:) */
public required init(wrappedRequired: WrappedInt) {}
// CHECK: {{^}} init(wrappedRequiredInSub: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequiredInSub:) */
public init(wrappedRequiredInSub: WrappedInt) {}
// CHECK: dynamic init(wrappedDynamic: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrappedDynamic:) */
@objc public dynamic init(wrappedDynamic: WrappedInt) {}
// CHECK: dynamic required init(wrappedRequiredDynamic: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequiredDynamic:) */
@objc public dynamic required init(wrappedRequiredDynamic: WrappedInt) {}
public func lastMethod() {}
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// This is mostly to check when changes are necessary for the CHECK-IR lines
// above.
// CHECK-VTABLE-LABEL: sil_vtable [serialized] User {
// (10 words of normal class metadata on 64-bit platforms, 13 on 32-bit)
// 10 CHECK-VTABLE-NEXT: #User.unwrappedProp!getter.1:
// 11 CHECK-VTABLE-NEXT: #User.unwrappedProp!setter.1:
// 12 CHECK-VTABLE-NEXT: #User.unwrappedProp!materializeForSet.1:
// 13 CHECK-VTABLE-NEXT: #User.wrappedProp!getter.1:
// 14 CHECK-VTABLE-NEXT: #User.wrappedProp!setter.1:
// 15 CHECK-VTABLE-NEXT: #User.wrappedProp!materializeForSet.1:
// 16 CHECK-VTABLE-NEXT: #User.returnsUnwrappedMethod!1:
// 17 CHECK-VTABLE-NEXT: #User.returnsWrappedMethod!1:
// 18 CHECK-VTABLE-NEXT: #User.constrainedUnwrapped!1:
// 19 CHECK-VTABLE-NEXT: #User.constrainedWrapped!1:
// 20 CHECK-VTABLE-NEXT: #User.subscript!getter.1:
// 21 CHECK-VTABLE-NEXT: #User.subscript!getter.1:
// 22 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 23 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 24 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 25 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 26 CHECK-VTABLE-NEXT: #User.init!allocator.1:
// 27 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 28 CHECK-VTABLE-NEXT: #User.init!initializer.1:
// 29 CHECK-VTABLE-NEXT: #User.init!allocator.1:
// 30 CHECK-VTABLE-NEXT: #User.lastMethod!1:
// CHECK-VTABLE: }
// CHECK-LABEL: class UserConvenience
// CHECK-RECOVERY-LABEL: class UserConvenience
open class UserConvenience {
// CHECK: init()
// CHECK-RECOVERY: init()
public init() {}
// CHECK: convenience init(wrapped: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
public convenience init(wrapped: WrappedInt) { self.init() }
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
public convenience init(conveniently: Int) { self.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-LABEL: class UserDynamic
// CHECK-RECOVERY-LABEL: class UserDynamic
open class UserDynamic {
// CHECK: init()
// CHECK-RECOVERY: init()
@objc public dynamic init() {}
// CHECK: init(wrapped: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
@objc public dynamic init(wrapped: WrappedInt) {}
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
@objc public dynamic convenience init(conveniently: Int) { self.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-LABEL: class UserDynamicConvenience
// CHECK-RECOVERY-LABEL: class UserDynamicConvenience
open class UserDynamicConvenience {
// CHECK: init()
// CHECK-RECOVERY: init()
@objc public dynamic init() {}
// CHECK: convenience init(wrapped: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
@objc public dynamic convenience init(wrapped: WrappedInt) { self.init() }
// CHECK: convenience init(conveniently: Int)
// CHECK-RECOVERY: convenience init(conveniently: Int)
@objc public dynamic convenience init(conveniently: Int) { self.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-LABEL: class UserSub
// CHECK-RECOVERY-LABEL: class UserSub
open class UserSub : User {
// CHECK: init(wrapped: WrappedInt?)
// CHECK-RECOVERY: /* placeholder for init(wrapped:) */
public override init(wrapped: WrappedInt?) { super.init() }
// CHECK: required init(wrappedRequired: WrappedInt?)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequired:) */
public required init(wrappedRequired: WrappedInt?) { super.init() }
// CHECK: required init(wrappedRequiredInSub: WrappedInt?)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequiredInSub:) */
public required override init(wrappedRequiredInSub: WrappedInt?) { super.init() }
// CHECK: required init(wrappedRequiredDynamic: WrappedInt)
// CHECK-RECOVERY: /* placeholder for init(wrappedRequiredDynamic:) */
public required init(wrappedRequiredDynamic: WrappedInt) { super.init() }
}
// CHECK: {{^}$}}
// CHECK-RECOVERY: {{^}$}}
// CHECK-DAG: let x: MysteryTypedef
// CHECK-RECOVERY-DAG: let x: Int32
public let x: MysteryTypedef = 0
public protocol HasAssoc {
associatedtype Assoc
}
extension ImportedType: HasAssoc {}
public struct AnotherType: HasAssoc {
public typealias Assoc = MysteryTypedef
}
public func useAssoc<T: HasAssoc>(_: T.Type) -> T.Assoc? { return nil }
// CHECK-DAG: let usesAssoc: ImportedType.Assoc?
// CHECK-RECOVERY-DAG: let usesAssoc: Int32?
public let usesAssoc = useAssoc(ImportedType.self)
// CHECK-DAG: let usesAssoc2: AnotherType.Assoc?
// CHECK-RECOVERY-DAG: let usesAssoc2: AnotherType.Assoc?
public let usesAssoc2 = useAssoc(AnotherType.self)
// CHECK-DAG: let wrapped: WrappedInt
// CHECK-RECOVERY-NEGATIVE-NOT: let wrapped:
public let wrapped = WrappedInt(0)
// CHECK-DAG: let unwrapped: UnwrappedInt
// CHECK-RECOVERY-DAG: let unwrapped: Int32
public let unwrapped: UnwrappedInt = 0
// CHECK-DAG: let wrappedMetatype: WrappedInt.Type
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedMetatype:
public let wrappedMetatype = WrappedInt.self
// CHECK-DAG: let wrappedOptional: WrappedInt?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedOptional:
public let wrappedOptional: WrappedInt? = nil
// CHECK-DAG: let wrappedIUO: WrappedInt!
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedIUO:
public let wrappedIUO: WrappedInt! = nil
// CHECK-DAG: let wrappedArray: [WrappedInt]
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedArray:
public let wrappedArray: [WrappedInt] = []
// CHECK-DAG: let wrappedDictionary: [Int : WrappedInt]
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedDictionary:
public let wrappedDictionary: [Int: WrappedInt] = [:]
// CHECK-DAG: let wrappedTuple: (WrappedInt, Int)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedTuple:
public let wrappedTuple: (WrappedInt, Int)? = nil
// CHECK-DAG: let wrappedTuple2: (Int, WrappedInt)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedTuple2:
public let wrappedTuple2: (Int, WrappedInt)? = nil
// CHECK-DAG: let wrappedClosure: ((WrappedInt) -> Void)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosure:
public let wrappedClosure: ((WrappedInt) -> Void)? = nil
// CHECK-DAG: let wrappedClosure2: (() -> WrappedInt)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosure2:
public let wrappedClosure2: (() -> WrappedInt)? = nil
// CHECK-DAG: let wrappedClosure3: ((Int, WrappedInt) -> Void)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosure3:
public let wrappedClosure3: ((Int, WrappedInt) -> Void)? = nil
// CHECK-DAG: let wrappedClosureInout: ((inout WrappedInt) -> Void)?
// CHECK-RECOVERY-NEGATIVE-NOT: let wrappedClosureInout:
public let wrappedClosureInout: ((inout WrappedInt) -> Void)? = nil
// CHECK-DAG: var wrappedFirst: WrappedInt?
// CHECK-DAG: var normalSecond: Int?
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedFirst:
// CHECK-RECOVERY-DAG: var normalSecond: Int?
public var wrappedFirst: WrappedInt?, normalSecond: Int?
// CHECK-DAG: var normalFirst: Int?
// CHECK-DAG: var wrappedSecond: WrappedInt?
// CHECK-RECOVERY-DAG: var normalFirst: Int?
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedSecond:
public var normalFirst: Int?, wrappedSecond: WrappedInt?
// CHECK-DAG: var wrappedThird: WrappedInt?
// CHECK-DAG: var wrappedFourth: WrappedInt?
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedThird:
// CHECK-RECOVERY-NEGATIVE-NOT: var wrappedFourth:
public var wrappedThird, wrappedFourth: WrappedInt?
// CHECK-DAG: func usesWrapped(_ wrapped: WrappedInt)
// CHECK-RECOVERY-NEGATIVE-NOT: func usesWrapped(
public func usesWrapped(_ wrapped: WrappedInt) {}
// CHECK-DAG: func usesUnwrapped(_ unwrapped: UnwrappedInt)
// CHECK-RECOVERY-DAG: func usesUnwrapped(_ unwrapped: Int32)
public func usesUnwrapped(_ unwrapped: UnwrappedInt) {}
// CHECK-DAG: func returnsWrapped() -> WrappedInt
// CHECK-RECOVERY-NEGATIVE-NOT: func returnsWrapped(
public func returnsWrapped() -> WrappedInt { fatalError() }
// CHECK-DAG: func returnsWrappedGeneric<T>(_: T.Type) -> WrappedInt
// CHECK-RECOVERY-NEGATIVE-NOT: func returnsWrappedGeneric<
public func returnsWrappedGeneric<T>(_: T.Type) -> WrappedInt { fatalError() }
public protocol WrappedProto {}
public protocol UnwrappedProto {}
public typealias WrappedAlias = WrappedInt
public typealias UnwrappedAlias = UnwrappedInt
public typealias ConstrainedWrapped<T: HasAssoc> = T where T.Assoc == WrappedInt
public typealias ConstrainedUnwrapped<T: HasAssoc> = T where T.Assoc == UnwrappedInt
#endif // TEST
| apache-2.0 | 5b651875bb1f54267976d610f5aacda7 | 42.4125 | 219 | 0.721797 | 3.941217 | false | false | false | false |
adrfer/swift | test/Sema/availability_versions.swift | 2 | 73799 | // RUN: %target-parse-verify-swift -target x86_64-apple-macosx10.50 -disable-objc-attr-requires-foundation-module
// RUN: not %target-swift-frontend -target x86_64-apple-macosx10.50 -disable-objc-attr-requires-foundation-module -parse %s 2>&1 | FileCheck %s '--implicit-check-not=<unknown>:0'
// Make sure we do not emit availability errors or warnings when -disable-availability-checking is passed
// RUN: not %target-swift-frontend -target x86_64-apple-macosx10.50 -parse -disable-objc-attr-requires-foundation-module -disable-availability-checking %s 2>&1 | FileCheck %s '--implicit-check-not=error:' '--implicit-check-not=warning:'
// REQUIRES: OS=macosx
func markUsed<T>(t: T) {}
@available(OSX, introduced=10.9)
func globalFuncAvailableOn10_9() -> Int { return 9 }
@available(OSX, introduced=10.51)
func globalFuncAvailableOn10_51() -> Int { return 10 }
@available(OSX, introduced=10.52)
func globalFuncAvailableOn10_52() -> Int { return 11 }
// Top level should reflect the minimum deployment target.
let ignored1: Int = globalFuncAvailableOn10_9()
let ignored2: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let ignored3: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// Functions without annotations should reflect the minimum deployment target.
func functionWithoutAvailability() {
let _: Int = globalFuncAvailableOn10_9()
let _: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
// Functions with annotations should refine their bodies.
@available(OSX, introduced=10.51)
func functionAvailableOn10_51() {
let _: Int = globalFuncAvailableOn10_9()
let _: Int = globalFuncAvailableOn10_51()
// Nested functions should get their own refinement context.
@available(OSX, introduced=10.52)
func innerFunctionAvailableOn10_52() {
let _: Int = globalFuncAvailableOn10_9()
let _: Int = globalFuncAvailableOn10_51()
let _: Int = globalFuncAvailableOn10_52()
}
let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
// Don't allow script-mode globals to marked potentially unavailable. Their
// initializers are eagerly executed.
@available(OSX, introduced=10.51) // expected-error {{global variable cannot be marked potentially unavailable with '@available' in script mode}}
var potentiallyUnavailableGlobalInScriptMode: Int = globalFuncAvailableOn10_51()
// Still allow other availability annotations on script-mode globals
@available(OSX, deprecated=10.51)
var deprecatedGlobalInScriptMode: Int = 5
if #available(OSX 10.51, *) {
let _: Int = globalFuncAvailableOn10_51()
let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
if #available(OSX 10.51, *) {
let _: Int = globalFuncAvailableOn10_51()
let _: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
} else {
let _: Int = globalFuncAvailableOn10_9()
let _: Int = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
@available(OSX, introduced=10.51)
@available(iOS, introduced=8.0)
func globalFuncAvailableOnOSX10_51AndiOS8_0() -> Int { return 10 }
if #available(OSX 10.51, iOS 8.0, *) {
let _: Int = globalFuncAvailableOnOSX10_51AndiOS8_0()
}
if #available(iOS 9.0, *) {
let _: Int = globalFuncAvailableOnOSX10_51AndiOS8_0() // expected-error {{'globalFuncAvailableOnOSX10_51AndiOS8_0()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
// Multiple unavailable references in a single statement
let ignored4: (Int, Int) = (globalFuncAvailableOn10_51(), globalFuncAvailableOn10_52()) // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}} expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 2{{add 'if #available' version check}}
globalFuncAvailableOn10_9()
let ignored5 = globalFuncAvailableOn10_51 // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// Overloaded global functions
@available(OSX, introduced=10.9)
func overloadedFunction() {}
@available(OSX, introduced=10.51)
func overloadedFunction(on1010: Int) {}
overloadedFunction()
overloadedFunction(0) // expected-error {{'overloadedFunction' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// Unavailable methods
class ClassWithUnavailableMethod {
@available(OSX, introduced=10.9)
func methAvailableOn10_9() {}
@available(OSX, introduced=10.51)
func methAvailableOn10_51() {}
@available(OSX, introduced=10.51)
class func classMethAvailableOn10_51() {}
func someOtherMethod() {
methAvailableOn10_9()
methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing instance method}}
// expected-note@-3 {{add 'if #available' version check}}
}
}
func callUnavailableMethods(o: ClassWithUnavailableMethod) {
let m10_9 = o.methAvailableOn10_9
m10_9()
let m10_51 = o.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
m10_51()
o.methAvailableOn10_9()
o.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
func callUnavailableMethodsViaIUO(o: ClassWithUnavailableMethod!) {
let m10_9 = o.methAvailableOn10_9
m10_9()
let m10_51 = o.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
m10_51()
o.methAvailableOn10_9()
o.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
func callUnavailableClassMethod() {
ClassWithUnavailableMethod.classMethAvailableOn10_51() // expected-error {{'classMethAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let m10_51 = ClassWithUnavailableMethod.classMethAvailableOn10_51 // expected-error {{'classMethAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
m10_51()
}
class SubClassWithUnavailableMethod : ClassWithUnavailableMethod {
func someMethod() {
methAvailableOn10_9()
methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing instance method}}
// expected-note@-3 {{add 'if #available' version check}}
}
}
class SubClassOverridingUnavailableMethod : ClassWithUnavailableMethod {
override func methAvailableOn10_51() {
methAvailableOn10_9()
super.methAvailableOn10_51() // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing instance method}}
// expected-note@-3 {{add 'if #available' version check}}
let m10_9 = super.methAvailableOn10_9
m10_9()
let m10_51 = super.methAvailableOn10_51 // expected-error {{'methAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing instance method}}
// expected-note@-3 {{add 'if #available' version check}}
m10_51()
}
func someMethod() {
methAvailableOn10_9()
// Calling our override should be fine
methAvailableOn10_51()
}
}
class ClassWithUnavailableOverloadedMethod {
@available(OSX, introduced=10.9)
func overloadedMethod() {}
@available(OSX, introduced=10.51)
func overloadedMethod(on1010: Int) {}
}
func callUnavailableOverloadedMethod(o: ClassWithUnavailableOverloadedMethod) {
o.overloadedMethod()
o.overloadedMethod(0) // expected-error {{'overloadedMethod' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
// Initializers
class ClassWithUnavailableInitializer {
@available(OSX, introduced=10.9)
required init() { }
@available(OSX, introduced=10.51)
required init(_ val: Int) { }
convenience init(s: String) {
self.init(5) // expected-error {{'init' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing initializer}}
// expected-note@-3 {{add 'if #available' version check}}
}
@available(OSX, introduced=10.51)
convenience init(onlyOn1010: String) {
self.init(5)
}
}
func callUnavailableInitializer() {
_ = ClassWithUnavailableInitializer()
_ = ClassWithUnavailableInitializer(5) // expected-error {{'init' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let i = ClassWithUnavailableInitializer.self
_ = i.init()
_ = i.init(5) // expected-error {{'init' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
class SuperWithWithUnavailableInitializer {
@available(OSX, introduced=10.9)
init() { }
@available(OSX, introduced=10.51)
init(_ val: Int) { }
}
class SubOfClassWithUnavailableInitializer : SuperWithWithUnavailableInitializer {
override init(_ val: Int) {
super.init(5) // expected-error {{'init' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing initializer}}
// expected-note@-3 {{add 'if #available' version check}}
}
override init() {
super.init()
}
@available(OSX, introduced=10.51)
init(on1010: Int) {
super.init(22)
}
}
// Properties
class ClassWithUnavailableProperties {
@available(OSX, introduced=10.9) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}}
var nonLazyAvailableOn10_9Stored: Int = 9
@available(OSX, introduced=10.51) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}}
var nonLazyAvailableOn10_51Stored : Int = 10
@available(OSX, introduced=10.51) // expected-error {{stored properties cannot be marked potentially unavailable with '@available'}}
let nonLazyLetAvailableOn10_51Stored : Int = 10
// Make sure that we don't emit a Fix-It to mark a stored property as potentially unavailable.
// We don't support potentially unavailable stored properties yet.
var storedPropertyOfUnavailableType: ClassAvailableOn10_51? = nil // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
@available(OSX, introduced=10.9)
lazy var availableOn10_9Stored: Int = 9
@available(OSX, introduced=10.51)
lazy var availableOn10_51Stored : Int = 10
@available(OSX, introduced=10.9)
var availableOn10_9Computed: Int {
get {
let _: Int = availableOn10_51Stored // expected-error {{'availableOn10_51Stored' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
let _: Int = availableOn10_51Stored
}
return availableOn10_9Stored
}
set(newVal) {
availableOn10_9Stored = newVal
}
}
@available(OSX, introduced=10.51)
var availableOn10_51Computed: Int {
get {
return availableOn10_51Stored
}
set(newVal) {
availableOn10_51Stored = newVal
}
}
var propWithSetterOnlyAvailableOn10_51 : Int {
get {
globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing var}}
// expected-note@-3 {{add 'if #available' version check}}
return 0
}
@available(OSX, introduced=10.51)
set(newVal) {
globalFuncAvailableOn10_51()
}
}
var propWithGetterOnlyAvailableOn10_51 : Int {
@available(OSX, introduced=10.51)
get {
globalFuncAvailableOn10_51()
return 0
}
set(newVal) {
globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing var}}
// expected-note@-3 {{add 'if #available' version check}}
}
}
var propWithGetterAndSetterOnlyAvailableOn10_51 : Int {
@available(OSX, introduced=10.51)
get {
return 0
}
@available(OSX, introduced=10.51)
set(newVal) {
}
}
var propWithSetterOnlyAvailableOn10_51ForNestedMemberRef : ClassWithUnavailableProperties {
get {
return ClassWithUnavailableProperties()
}
@available(OSX, introduced=10.51)
set(newVal) {
}
}
var propWithGetterOnlyAvailableOn10_51ForNestedMemberRef : ClassWithUnavailableProperties {
@available(OSX, introduced=10.51)
get {
return ClassWithUnavailableProperties()
}
set(newVal) {
}
}
}
@available(OSX, introduced=10.51)
class ClassWithReferencesInInitializers {
var propWithInitializer10_51: Int = globalFuncAvailableOn10_51()
var propWithInitializer10_52: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
lazy var lazyPropWithInitializer10_51: Int = globalFuncAvailableOn10_51()
lazy var lazyPropWithInitializer10_52: Int = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add @available attribute to enclosing var}}
}
func accessUnavailableProperties(o: ClassWithUnavailableProperties) {
// Stored properties
let _: Int = o.availableOn10_9Stored
let _: Int = o.availableOn10_51Stored // expected-error {{'availableOn10_51Stored' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
o.availableOn10_9Stored = 9
o.availableOn10_51Stored = 10 // expected-error {{'availableOn10_51Stored' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
// Computed Properties
let _: Int = o.availableOn10_9Computed
let _: Int = o.availableOn10_51Computed // expected-error {{'availableOn10_51Computed' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
o.availableOn10_9Computed = 9
o.availableOn10_51Computed = 10 // expected-error {{'availableOn10_51Computed' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
// Getter allowed on 10.9 but setter is not
let _: Int = o.propWithSetterOnlyAvailableOn10_51
o.propWithSetterOnlyAvailableOn10_51 = 5 // expected-error {{setter for 'propWithSetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
// Setter is allowed on 10.51 and greater
o.propWithSetterOnlyAvailableOn10_51 = 5
}
// Setter allowed on 10.9 but getter is not
o.propWithGetterOnlyAvailableOn10_51 = 5
let _: Int = o.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
// Getter is allowed on 10.51 and greater
let _: Int = o.propWithGetterOnlyAvailableOn10_51
}
// Tests for nested member refs
// Both getters are potentially unavailable.
let _: Int = o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available on OS X 10.51 or newer}} expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 2{{add @available attribute to enclosing global function}}
// expected-note@-2 2{{add 'if #available' version check}}
// Nested getter is potentially unavailable, outer getter is available
let _: Int = o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.propWithSetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
// Nested getter is available, outer getter is potentially unavailable
let _:Int = o.propWithSetterOnlyAvailableOn10_51ForNestedMemberRef.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
// Both getters are always available.
let _: Int = o.propWithSetterOnlyAvailableOn10_51ForNestedMemberRef.propWithSetterOnlyAvailableOn10_51
// Nesting in source of assignment
var v: Int
v = o.propWithGetterOnlyAvailableOn10_51 // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
v = (o.propWithGetterOnlyAvailableOn10_51) // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
// Inout requires access to both getter and setter
func takesInout(inout i : Int) { }
takesInout(&o.propWithGetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because getter for 'propWithGetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
takesInout(&o.propWithSetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because setter for 'propWithSetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
takesInout(&o.propWithGetterAndSetterOnlyAvailableOn10_51) // expected-error {{cannot pass as inout because getter for 'propWithGetterAndSetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}} expected-error {{cannot pass as inout because setter for 'propWithGetterAndSetterOnlyAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 2{{add @available attribute to enclosing global function}}
// expected-note@-2 2{{add 'if #available' version check}}
takesInout(&o.availableOn10_9Computed)
takesInout(&o.propWithGetterOnlyAvailableOn10_51ForNestedMemberRef.availableOn10_9Computed) // expected-error {{getter for 'propWithGetterOnlyAvailableOn10_51ForNestedMemberRef' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
// _silgen_name
@_silgen_name("SomeName")
@available(OSX, introduced=10.51)
func funcWith_silgen_nameAvailableOn10_51(p: ClassAvailableOn10_51?) -> ClassAvailableOn10_51
// Enums
@available(OSX, introduced=10.51)
enum EnumIntroducedOn10_51 {
case Element
}
@available(OSX, introduced=10.52)
enum EnumIntroducedOn10_52 {
case Element
}
@available(OSX, introduced=10.51)
enum CompassPoint {
case North
case South
case East
@available(OSX, introduced=10.52)
case West
case WithAvailableByEnumPayload(p : EnumIntroducedOn10_51)
@available(OSX, introduced=10.52)
case WithAvailableByEnumElementPayload(p : EnumIntroducedOn10_52)
@available(OSX, introduced=10.52)
case WithAvailableByEnumElementPayload1(p : EnumIntroducedOn10_52), WithAvailableByEnumElementPayload2(p : EnumIntroducedOn10_52)
case WithUnavailablePayload(p : EnumIntroducedOn10_52) // expected-error {{'EnumIntroducedOn10_52' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add @available attribute to enclosing case}}
case WithUnavailablePayload1(p : EnumIntroducedOn10_52), WithUnavailablePayload2(p : EnumIntroducedOn10_52) // expected-error 2{{'EnumIntroducedOn10_52' is only available on OS X 10.52 or newer}}
// expected-note@-1 2{{add @available attribute to enclosing case}}
}
@available(OSX, introduced=10.52)
func functionTakingEnumIntroducedOn10_52(e: EnumIntroducedOn10_52) { }
func useEnums() {
let _: CompassPoint = .North // expected-error {{'CompassPoint' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
let _: CompassPoint = .North
let _: CompassPoint = .West // expected-error {{'West' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
if #available(OSX 10.52, *) {
let _: CompassPoint = .West
}
// Pattern matching on an enum element does not require it to be definitely available
if #available(OSX 10.51, *) {
let point: CompassPoint = .North
switch (point) {
case .North, .South, .East:
markUsed("NSE")
case .West: // We do not expect an error here
markUsed("W")
case .WithAvailableByEnumElementPayload(let p):
markUsed("WithAvailableByEnumElementPayload")
// For the moment, we do not incorporate enum element availability into
// TRC construction. Perhaps we should?
functionTakingEnumIntroducedOn10_52(p) // expected-error {{'functionTakingEnumIntroducedOn10_52' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
}
}
// Classes
@available(OSX, introduced=10.9)
class ClassAvailableOn10_9 {
func someMethod() {}
class func someClassMethod() {}
var someProp : Int = 22
}
@available(OSX, introduced=10.51)
class ClassAvailableOn10_51 { // expected-note {{enclosing scope here}}
func someMethod() {}
class func someClassMethod() {
let _ = ClassAvailableOn10_51()
}
var someProp : Int = 22
@available(OSX, introduced=10.9) // expected-error {{declaration cannot be more available than enclosing scope}}
func someMethodAvailableOn10_9() { }
@available(OSX, introduced=10.52)
var propWithGetter: Int { // expected-note{{enclosing scope here}}
@available(OSX, introduced=10.51) // expected-error {{declaration cannot be more available than enclosing scope}}
get { return 0 }
}
}
func classAvailability() {
ClassAvailableOn10_9.someClassMethod()
ClassAvailableOn10_51.someClassMethod() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
ClassAvailableOn10_9.self
ClassAvailableOn10_51.self // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let o10_9 = ClassAvailableOn10_9()
let o10_51 = ClassAvailableOn10_51() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
o10_9.someMethod()
o10_51.someMethod()
let _ = o10_9.someProp
let _ = o10_51.someProp
}
func castingUnavailableClass(o : AnyObject) {
let _ = o as! ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _ = o as? ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _ = o is ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
protocol Createable {
init()
}
@available(OSX, introduced=10.51)
class ClassAvailableOn10_51_Createable : Createable {
required init() {}
}
func create<T : Createable>() -> T {
return T()
}
class ClassWithGenericTypeParameter<T> { }
class ClassWithTwoGenericTypeParameter<T, S> { }
func classViaTypeParameter() {
let _ : ClassAvailableOn10_51_Createable = // expected-error {{'ClassAvailableOn10_51_Createable' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
create()
let _ = create() as
ClassAvailableOn10_51_Createable // expected-error {{'ClassAvailableOn10_51_Createable' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _ = [ClassAvailableOn10_51]() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _: ClassWithGenericTypeParameter<ClassAvailableOn10_51> = ClassWithGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _: ClassWithTwoGenericTypeParameter<ClassAvailableOn10_51, String> = ClassWithTwoGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _: ClassWithTwoGenericTypeParameter<String, ClassAvailableOn10_51> = ClassWithTwoGenericTypeParameter() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _: ClassWithTwoGenericTypeParameter<ClassAvailableOn10_51, ClassAvailableOn10_51> = ClassWithTwoGenericTypeParameter() // expected-error 2{{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 2{{add @available attribute to enclosing global function}}
// expected-note@-2 2{{add 'if #available' version check}}
let _: ClassAvailableOn10_51? = nil // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
// Unavailable class used in declarations
class ClassWithDeclarationsOfUnavailableClasses {
@available(OSX, introduced=10.51)
init() {
unavailablePropertyOfUnavailableType = ClassAvailableOn10_51()
unavailablePropertyOfUnavailableType = ClassAvailableOn10_51()
}
var propertyOfUnavailableType: ClassAvailableOn10_51 // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
@available(OSX, introduced=10.51)
lazy var unavailablePropertyOfUnavailableType: ClassAvailableOn10_51 = ClassAvailableOn10_51()
@available(OSX, introduced=10.51)
lazy var unavailablePropertyOfOptionalUnavailableType: ClassAvailableOn10_51? = nil
@available(OSX, introduced=10.51)
lazy var unavailablePropertyOfUnavailableTypeWithInitializer: ClassAvailableOn10_51 = ClassAvailableOn10_51()
@available(OSX, introduced=10.51)
static var unavailableStaticPropertyOfUnavailableType: ClassAvailableOn10_51 = ClassAvailableOn10_51()
@available(OSX, introduced=10.51)
static var unavailableStaticPropertyOfOptionalUnavailableType: ClassAvailableOn10_51?
func methodWithUnavailableParameterType(o : ClassAvailableOn10_51) { // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing instance method}}
}
@available(OSX, introduced=10.51)
func unavailableMethodWithUnavailableParameterType(o : ClassAvailableOn10_51) {
}
func methodWithUnavailableReturnType() -> ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing instance method}}
return ClassAvailableOn10_51() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing instance method}}
// expected-note@-3 {{add 'if #available' version check}}
}
@available(OSX, introduced=10.51)
func unavailableMethodWithUnavailableReturnType() -> ClassAvailableOn10_51 {
return ClassAvailableOn10_51()
}
func methodWithUnavailableLocalDeclaration() {
let _ : ClassAvailableOn10_51 = methodWithUnavailableReturnType() // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add @available attribute to enclosing instance method}}
// expected-note@-3 {{add 'if #available' version check}}
}
@available(OSX, introduced=10.51)
func unavailableMethodWithUnavailableLocalDeclaration() {
let _ : ClassAvailableOn10_51 = methodWithUnavailableReturnType()
}
}
func referToUnavailableStaticProperty() {
let _ = ClassWithDeclarationsOfUnavailableClasses.unavailableStaticPropertyOfUnavailableType // expected-error {{'unavailableStaticPropertyOfUnavailableType' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
class ClassExtendingUnavailableClass : ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
}
@available(OSX, introduced=10.51)
class UnavailableClassExtendingUnavailableClass : ClassAvailableOn10_51 {
}
// Method availability is contravariant
class SuperWithAlwaysAvailableMembers {
func shouldAlwaysBeAvailableMethod() { // expected-note {{overridden declaration is here}}
}
var shouldAlwaysBeAvailableProperty: Int { // expected-note {{overridden declaration is here}}
get { return 9 }
set(newVal) {}
}
var setterShouldAlwaysBeAvailableProperty: Int {
get { return 9 }
set(newVal) {} // expected-note {{overridden declaration is here}}
}
var getterShouldAlwaysBeAvailableProperty: Int {
get { return 9 } // expected-note {{overridden declaration is here}}
set(newVal) {}
}
}
class SubWithLimitedMemberAvailability : SuperWithAlwaysAvailableMembers {
@available(OSX, introduced=10.51)
override func shouldAlwaysBeAvailableMethod() { // expected-error {{overriding 'shouldAlwaysBeAvailableMethod' must be as available as declaration it overrides}}
}
@available(OSX, introduced=10.51)
override var shouldAlwaysBeAvailableProperty: Int { // expected-error {{overriding 'shouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}}
get { return 10 }
set(newVal) {}
}
override var setterShouldAlwaysBeAvailableProperty: Int {
get { return 9 }
@available(OSX, introduced=10.51)
set(newVal) {} // expected-error {{overriding setter for 'setterShouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}}
// This is a terrible diagnostic. rdar://problem/20427938
}
override var getterShouldAlwaysBeAvailableProperty: Int {
@available(OSX, introduced=10.51)
get { return 9 } // expected-error {{overriding getter for 'getterShouldAlwaysBeAvailableProperty' must be as available as declaration it overrides}}
set(newVal) {}
}
}
class SuperWithLimitedMemberAvailability {
@available(OSX, introduced=10.51)
func someMethod() {
}
@available(OSX, introduced=10.51)
var someProperty: Int {
get { return 10 }
set(newVal) {}
}
}
class SubWithLargerMemberAvailability : SuperWithLimitedMemberAvailability {
@available(OSX, introduced=10.9)
override func someMethod() {
super.someMethod() // expected-error {{'someMethod()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
super.someMethod()
}
}
@available(OSX, introduced=10.9)
override var someProperty: Int {
get {
let _ = super.someProperty // expected-error {{'someProperty' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing class}}
// expected-note@-2 {{add 'if #available' version check}}
if #available(OSX 10.51, *) {
let _ = super.someProperty
}
return 9
}
set(newVal) {}
}
}
// Inheritance and availability
@available(OSX, introduced=10.51)
protocol ProtocolAvailableOn10_9 {
}
@available(OSX, introduced=10.51)
protocol ProtocolAvailableOn10_51 {
}
@available(OSX, introduced=10.9)
protocol ProtocolAvailableOn10_9InheritingFromProtocolAvailableOn10_51 : ProtocolAvailableOn10_51 {
}
@available(OSX, introduced=10.51)
protocol ProtocolAvailableOn10_51InheritingFromProtocolAvailableOn10_9 : ProtocolAvailableOn10_9 {
}
@available(OSX, introduced=10.9)
class SubclassAvailableOn10_9OfClassAvailableOn10_51 : ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
}
// We allow nominal types to conform to protocols that are less available than the types themselves.
@available(OSX, introduced=10.9)
class ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51 : ProtocolAvailableOn10_51 {
}
func castToUnavailableProtocol() {
let o: ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51 = ClassAvailableOn10_9AdoptingProtocolAvailableOn10_51()
let _: ProtocolAvailableOn10_51 = o // expected-error {{'ProtocolAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _ = o as ProtocolAvailableOn10_51 // expected-error {{'ProtocolAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
@available(OSX, introduced=10.9)
class SubclassAvailableOn10_9OfClassAvailableOn10_51AlsoAdoptingProtocolAvailableOn10_51 : ClassAvailableOn10_51 { // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
}
class SomeGenericClass<T> { }
@available(OSX, introduced=10.9)
class SubclassAvailableOn10_9OfSomeGenericClassOfProtocolAvailableOn10_51 : SomeGenericClass<ProtocolAvailableOn10_51> { // expected-error {{'ProtocolAvailableOn10_51' is only available on OS X 10.51 or newer}}
}
func GenericWhereClause<T where T: ProtocolAvailableOn10_51>(t: T) { // expected-error * {{'ProtocolAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 * {{add @available attribute to enclosing global function}}
}
func GenericSignature<T : ProtocolAvailableOn10_51>(t: T) { // expected-error * {{'ProtocolAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 * {{add @available attribute to enclosing global function}}
}
// Extensions
extension ClassAvailableOn10_51 { } // expected-error {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing extension}}
@available(OSX, introduced=10.51)
extension ClassAvailableOn10_51 {
func m() {
let _ = globalFuncAvailableOn10_51()
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add @available attribute to enclosing instance method}}
// expected-note@-2 {{add 'if #available' version check}}
}
}
class ClassToExtend { }
@available(OSX, introduced=10.51)
extension ClassToExtend {
func extensionMethod() { }
@available(OSX, introduced=10.52)
func extensionMethod10_52() { }
class ExtensionClass { }
// We rely on not allowing nesting of extensions, so test to make sure
// this emits an error.
// CHECK:error: declaration is only valid at file scope
extension ClassToExtend { } // expected-error {{declaration is only valid at file scope}}
}
// We allow protocol extensions for protocols that are less available than the
// conforming class.
extension ClassToExtend : ProtocolAvailableOn10_51 {
}
@available(OSX, introduced=10.51)
extension ClassToExtend { // expected-note {{enclosing scope here}}
@available(OSX, introduced=10.9) // expected-error {{declaration cannot be more available than enclosing scope}}
func extensionMethod10_9() { }
}
func useUnavailableExtension() {
let o = ClassToExtend()
o.extensionMethod() // expected-error {{'extensionMethod()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
let _ = ClassToExtend.ExtensionClass() // expected-error {{'ExtensionClass' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
o.extensionMethod10_52() // expected-error {{'extensionMethod10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
// Useless #available(...) checks
func functionWithDefaultAvailabilityAndUselessCheck(p: Bool) {
// Default availability reflects minimum deployment: 10.9 and up
if #available(OSX 10.9, *) { // expected-warning {{unnecessary check for 'OSX'; minimum deployment target ensures guard will always be true}}
let _ = globalFuncAvailableOn10_9()
}
if #available(OSX 10.51, *) { // expected-note {{enclosing scope here}}
let _ = globalFuncAvailableOn10_51()
if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}}
let _ = globalFuncAvailableOn10_51()
}
}
if #available(OSX 10.9, *) { // expected-note {{enclosing scope here}} expected-warning {{unnecessary check for 'OSX'; minimum deployment target ensures guard will always be true}}
} else {
// Make sure we generate a warning about an unnecessary check even if the else branch of if is dead.
if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}}
}
}
// This 'if' is strictly to limit the scope of the guard fallthrough
if p {
guard #available(OSX 10.9, *) else { // expected-note {{enclosing scope here}} expected-warning {{unnecessary check for 'OSX'; minimum deployment target ensures guard will always be true}}
// Make sure we generate a warning about an unnecessary check even if the else branch of guard is dead.
if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}}
}
}
}
// We don't want * generate a warn about useless checks; the check may be required on
// another platform
if #available(iOS 8.0, *) {
}
if #available(OSX 10.51, *) {
// Similarly do not want '*' to generate a warning in a refined TRC.
if #available(iOS 8.0, *) {
}
}
}
@available(OSX, unavailable)
func explicitlyUnavailable() { } // expected-note 2{{'explicitlyUnavailable()' has been explicitly marked unavailable here}}
func functionWithUnavailableInDeadBranch() {
if #available(iOS 8.0, *) {
} else {
// This branch is dead on OSX, so we shouldn't a warning about use of potentially unavailable APIs in it.
globalFuncAvailableOn10_51() // no-warning
@available(OSX 10.51, *)
func localFuncAvailableOn10_51() {
globalFuncAvailableOn10_52() // no-warning
}
localFuncAvailableOn10_51() // no-warning
// We still want to error on references to explicitly unavailable symbols
// CHECK:error: 'explicitlyUnavailable()' is unavailable
explicitlyUnavailable() // expected-error {{'explicitlyUnavailable()' is unavailable}}
}
guard #available(iOS 8.0, *) else {
globalFuncAvailableOn10_51() // no-warning
// CHECK:error: 'explicitlyUnavailable()' is unavailable
explicitlyUnavailable() // expected-error {{'explicitlyUnavailable()' is unavailable}}
}
}
@available(OSX, introduced=10.51)
func functionWithSpecifiedAvailabilityAndUselessCheck() { // expected-note 2{{enclosing scope here}}
if #available(OSX 10.9, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}}
let _ = globalFuncAvailableOn10_9()
}
if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}}
let _ = globalFuncAvailableOn10_51()
}
}
// #available(...) outside if statement guards
func injectToOptional<T>(v: T) -> T? {
return v
}
if let _ = injectToOptional(5), #available(OSX 10.52, *) {} // ok
// Refining context inside guard
if #available(OSX 10.51, *),
let _ = injectToOptional(globalFuncAvailableOn10_51()),
let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _ = globalFuncAvailableOn10_51()
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
if let _ = injectToOptional(5), #available(OSX 10.51, *),
let _ = injectToOptional(globalFuncAvailableOn10_51()),
let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _ = globalFuncAvailableOn10_51()
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
if let _ = injectToOptional(globalFuncAvailableOn10_51()), #available(OSX 10.51, *), // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
let _ = injectToOptional(globalFuncAvailableOn10_52()) { // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
if let _ = injectToOptional(5), #available(OSX 10.51, *), // expected-note {{enclosing scope here}}
let _ = injectToOptional(6), #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}}
}
// Tests for the guard control construct.
func useGuardAvailable() {
// Guard fallthrough should refine context
guard #available(OSX 10.51, *) else { // expected-note {{enclosing scope here}}
let _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// expected-note@-2 {{add @available attribute to enclosing global function}}
return
}
let _ = globalFuncAvailableOn10_51()
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// expected-note@-2 {{add @available attribute to enclosing global function}}
if #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}}
}
if globalFuncAvailableOn10_51() > 0 {
guard #available(OSX 10.52, *),
let x = injectToOptional(globalFuncAvailableOn10_52()) else { return }
_ = x
}
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// expected-note@-2 {{add @available attribute to enclosing global function}}
}
func twoGuardsInSameBlock(p: Int) {
if (p > 0) {
guard #available(OSX 10.51, *) else { return }
let _ = globalFuncAvailableOn10_51()
guard #available(OSX 10.52, *) else { return }
let _ = globalFuncAvailableOn10_52()
}
let _ = globalFuncAvailableOn10_51() // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
// expected-note@-2 {{add @available attribute to enclosing global function}}
}
// Refining while loops
while globalFuncAvailableOn10_51() > 10 { } // expected-error {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
while #available(OSX 10.51, *), // expected-note {{enclosing scope here}}
globalFuncAvailableOn10_51() > 10 {
let _ = globalFuncAvailableOn10_51()
let _ = globalFuncAvailableOn10_52() // expected-error {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
while globalFuncAvailableOn10_51() > 11,
let _ = injectToOptional(5),
#available(OSX 10.52, *) {
let _ = globalFuncAvailableOn10_52();
}
while #available(OSX 10.51, *) { // expected-warning {{unnecessary check for 'OSX'; enclosing scope ensures guard will always be true}}
}
}
// Tests for Fix-It replacement text
// The whitespace in the replacement text is particularly important here -- it reflects the level
// of indentation for the added if #available() or @available attribute. Note that, for the moment, we hard
// code *added* indentation in Fix-Its as 4 spaces (that is, when indenting in a Fix-It, we
// take whatever indentation was there before and add 4 spaces to it).
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{1-27=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n} else {\n // Fallback on earlier versions\n}}}
let declForFixitAtTopLevel: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{1-57=if #available(OSX 10.51, *) {\n let declForFixitAtTopLevel: ClassAvailableOn10_51? = nil\n} else {\n // Fallback on earlier versions\n}}}
func fixitForReferenceInGlobalFunction() {
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing global function}} {{1-1=@available(OSX 10.51, *)\n}}
}
public func fixitForReferenceInGlobalFunctionWithDeclModifier() {
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing global function}} {{1-1=@available(OSX 10.51, *)\n}}
}
@noreturn
func fixitForReferenceInGlobalFunctionWithAttribute() {
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{3-29=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing global function}} {{1-1=@available(OSX 10.51, *)\n}}
}
func takesAutoclosure(@autoclosure c : () -> ()) {
}
class ClassForFixit {
func fixitForReferenceInMethod() {
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{5-31=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing instance method}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-4 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
}
func fixitForReferenceNestedInMethod() {
func inner() {
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing instance method}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-4 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
}
let _: () -> () = { () in
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing instance method}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-4 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
}
takesAutoclosure(functionAvailableOn10_51())
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{5-49=if #available(OSX 10.51, *) {\n takesAutoclosure(functionAvailableOn10_51())\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing instance method}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-4 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
}
var fixitForReferenceInPropertyAccessor: Int {
get {
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{7-33=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing var}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-4 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
return 5
}
}
var fixitForReferenceInPropertyType: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
lazy var fixitForReferenceInLazyPropertyType: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add @available attribute to enclosing var}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-3 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
private lazy var fixitForReferenceInPrivateLazyPropertyType: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add @available attribute to enclosing var}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-3 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
lazy private var fixitForReferenceInLazyPrivatePropertyType: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add @available attribute to enclosing var}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-3 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
static var fixitForReferenceInStaticPropertyType: ClassAvailableOn10_51? = nil
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add @available attribute to enclosing class var}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-3 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
var fixitForReferenceInPropertyTypeMultiple: ClassAvailableOn10_51? = nil, other: Int = 7
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
func fixitForRefInGuardOfIf() {
if (globalFuncAvailableOn10_51() > 1066) {
let _ = 5
let _ = 6
}
// expected-error@-4 {{'globalFuncAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-5 {{add 'if #available' version check}} {{5-6=if #available(OSX 10.51, *) {\n if (globalFuncAvailableOn10_51() > 1066) {\n let _ = 5\n let _ = 6\n }\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-6 {{add @available attribute to enclosing instance method}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-7 {{add @available attribute to enclosing class}} {{1-1=@available(OSX 10.51, *)\n}}
}
}
extension ClassToExtend {
func fixitForReferenceInExtensionMethod() {
functionAvailableOn10_51()
// expected-error@-1 {{'functionAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{5-31=if #available(OSX 10.51, *) {\n functionAvailableOn10_51()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing instance method}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-4 {{add @available attribute to enclosing extension}} {{1-1=@available(OSX 10.51, *)\n}}
}
}
enum EnumForFixit {
case CaseWithUnavailablePayload(p: ClassAvailableOn10_51)
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add @available attribute to enclosing case}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-3 {{add @available attribute to enclosing enum}} {{1-1=@available(OSX 10.51, *)\n}}
case CaseWithUnavailablePayload2(p: ClassAvailableOn10_51), WithoutPayload
// expected-error@-1 {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-2 {{add @available attribute to enclosing case}} {{3-3=@available(OSX 10.51, *)\n }}
// expected-note@-3 {{add @available attribute to enclosing enum}} {{1-1=@available(OSX 10.51, *)\n}}
}
@objc
class Y {
var z = 0
}
@objc
class X {
var y = Y()
}
func testForFixitWithNestedMemberRefExpr() {
let x = X()
x.y.z = globalFuncAvailableOn10_52()
// expected-error@-1 {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{3-39=if #available(OSX 10.52, *) {\n x.y.z = globalFuncAvailableOn10_52()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing global function}} {{1-1=@available(OSX 10.52, *)\n}}
// Access via dynamic member reference
let anyX: AnyObject = x
anyX.y?.z = globalFuncAvailableOn10_52()
// expected-error@-1 {{'globalFuncAvailableOn10_52()' is only available on OS X 10.52 or newer}}
// expected-note@-2 {{add 'if #available' version check}} {{3-43=if #available(OSX 10.52, *) {\n anyX.y?.z = globalFuncAvailableOn10_52()\n } else {\n // Fallback on earlier versions\n }}}
// expected-note@-3 {{add @available attribute to enclosing global function}} {{1-1=@available(OSX 10.52, *)\n}}
}
// Protocol Conformances
protocol ProtocolWithRequirementMentioningUnavailable {
func hasUnavailableParameter(p: ClassAvailableOn10_51) // expected-error * {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 * {{add @available attribute to enclosing instance method}}
// expected-note@-2 * {{add @available attribute to enclosing protocol}}
func hasUnavailableReturn() -> ClassAvailableOn10_51 // expected-error * {{'ClassAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 * {{add @available attribute to enclosing instance method}}
// expected-note@-2 * {{add @available attribute to enclosing protocol}}
@available(OSX 10.51, *)
func hasUnavailableWithAnnotation(p: ClassAvailableOn10_51) -> ClassAvailableOn10_51
}
protocol HasMethodF {
associatedtype T
func f(p: T) // expected-note 5{{protocol requirement here}}
}
class TriesToConformWithFunctionIntroducedOn10_51 : HasMethodF { // expected-note {{conformance introduced here}}
@available(OSX, introduced=10.51)
func f(p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available on OS X 10.50.0 and newer}}
}
class ConformsWithFunctionIntroducedOnMinimumDeploymentTarget : HasMethodF {
// Even though this function is less available than its requirement,
// it is available on a deployment targets, so the conformance is safe.
@available(OSX, introduced=10.9)
func f(p: Int) { }
}
class SuperHasMethodF {
@available(OSX, introduced=10.51)
func f(p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available on OS X 10.50.0 and newer}}
}
class TriesToConformWithUnavailableFunctionInSuperClass : SuperHasMethodF, HasMethodF { // expected-note {{conformance introduced here}}
// The conformance here is generating an error on f in the super class.
}
@available(OSX, introduced=10.51)
class ConformsWithUnavailableFunctionInSuperClass : SuperHasMethodF, HasMethodF {
// Limiting this class to only be available on 10.51 and newer means that
// the witness in SuperHasMethodF is safe for the requirement on HasMethodF.
// in order for this class to be referenced we must be running on 10.51 or
// greater.
}
class ConformsByOverridingFunctionInSuperClass : SuperHasMethodF, HasMethodF {
// Now the witness is this f() (which is always available) and not the f()
// from the super class, so conformance is safe.
override func f(p: Int) { }
}
// Attempt to conform in protocol extension with unavailable witness
// in extension
class HasNoMethodF1 { }
extension HasNoMethodF1 : HasMethodF { // expected-note {{conformance introduced here}}
@available(OSX, introduced=10.51)
func f(p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available on OS X 10.50.0 and newer}}
}
class HasNoMethodF2 { }
@available(OSX, introduced=10.51)
extension HasNoMethodF2 : HasMethodF { // expected-note {{conformance introduced here}}
func f(p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available on OS X 10.50.0 and newer}}
}
@available(OSX, introduced=10.51)
class HasNoMethodF3 { }
@available(OSX, introduced=10.51)
extension HasNoMethodF3 : HasMethodF {
// We expect this conformance to succeed because on every version where HasNoMethodF3
// is available, HasNoMethodF3's f() is as available as the protocol requirement
func f(p: Int) { }
}
@available(OSX, introduced=10.51)
protocol HasMethodFOn10_51 {
func f(p: Int) // expected-note {{protocol requirement here}}
}
class ConformsToUnavailableProtocolWithUnavailableWitness : HasMethodFOn10_51 {
@available(OSX, introduced=10.51)
func f(p: Int) { }
}
@available(OSX, introduced=10.51)
class HasNoMethodF4 { }
@available(OSX, introduced=10.52)
extension HasNoMethodF4 : HasMethodFOn10_51 { // expected-note {{conformance introduced here}}
func f(p: Int) { } // expected-error {{protocol 'HasMethodFOn10_51' requires 'f' to be available on OS X 10.51 and newer}}
}
@available(OSX, introduced=10.51)
protocol HasTakesClassAvailableOn10_51 {
func takesClassAvailableOn10_51(o: ClassAvailableOn10_51) // expected-note 2{{protocol requirement here}}
}
class AttemptsToConformToHasTakesClassAvailableOn10_51 : HasTakesClassAvailableOn10_51 { // expected-note {{conformance introduced here}}
@available(OSX, introduced=10.52)
func takesClassAvailableOn10_51(o: ClassAvailableOn10_51) { // expected-error {{protocol 'HasTakesClassAvailableOn10_51' requires 'takesClassAvailableOn10_51' to be available on OS X 10.51 and newer}}
}
}
class ConformsToHasTakesClassAvailableOn10_51 : HasTakesClassAvailableOn10_51 {
@available(OSX, introduced=10.51)
func takesClassAvailableOn10_51(o: ClassAvailableOn10_51) {
}
}
class TakesClassAvailableOn10_51_A { }
extension TakesClassAvailableOn10_51_A : HasTakesClassAvailableOn10_51 { // expected-note {{conformance introduced here}}
@available(OSX, introduced=10.52)
func takesClassAvailableOn10_51(o: ClassAvailableOn10_51) { // expected-error {{protocol 'HasTakesClassAvailableOn10_51' requires 'takesClassAvailableOn10_51' to be available on OS X 10.51 and newer}}
}
}
class TakesClassAvailableOn10_51_B { }
extension TakesClassAvailableOn10_51_B : HasTakesClassAvailableOn10_51 {
@available(OSX, introduced=10.51)
func takesClassAvailableOn10_51(o: ClassAvailableOn10_51) {
}
}
// We do not want potential unavailability to play a role in picking a witness for a
// protocol requirement. Rather, the witness should be chosen, regardless of its
// potential unavailability, and then it should be diagnosed if it is less available
// than the protocol requires.
class TestAvailabilityDoesNotAffectWitnessCandidacy : HasMethodF { // expected-note {{conformance introduced here}}
// Test that we choose the more specialized witness even though it is
// less available than the protocol requires and there is a less specialized
// witness that has suitable availability.
@available(OSX, introduced=10.51)
func f(p: Int) { } // expected-error {{protocol 'HasMethodF' requires 'f' to be available on OS X 10.50.0 and newer}}
func f<T>(p: T) { }
}
protocol HasUnavailableMethodF {
@available(OSX, introduced=10.51)
func f(p: String)
}
class ConformsWithUnavailableFunction : HasUnavailableMethodF {
@available(OSX, introduced=10.9)
func f(p: String) { }
}
func useUnavailableProtocolMethod(h: HasUnavailableMethodF) {
h.f("Foo") // expected-error {{'f' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
func useUnavailableProtocolMethod<H : HasUnavailableMethodF> (h: H) {
h.f("Foo") // expected-error {{'f' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
// Short-form @available() annotations
@available(OSX 10.51, *)
class ClassWithShortFormAvailableOn10_51 {
}
@available(OSX 10.53, *)
class ClassWithShortFormAvailableOn10_53 {
}
@available(OSX 10.54, *)
class ClassWithShortFormAvailableOn10_54 {
}
@available(OSX 10.9, *)
func funcWithShortFormAvailableOn10_9() {
let _ = ClassWithShortFormAvailableOn10_51() // expected-error {{'ClassWithShortFormAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
@available(OSX 10.51, *)
func funcWithShortFormAvailableOn10_51() {
let _ = ClassWithShortFormAvailableOn10_51()
}
@available(iOS 14.0, *)
func funcWithShortFormAvailableOniOS14() {
let _ = ClassWithShortFormAvailableOn10_51() // expected-error {{'ClassWithShortFormAvailableOn10_51' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
}
@available(iOS 14.0, OSX 10.53, *)
func funcWithShortFormAvailableOniOS14AndOSX10_53() {
let _ = ClassWithShortFormAvailableOn10_51()
}
// Not idiomatic but we need to be able to handle it.
@available(iOS 8.0, *)
@available(OSX 10.51, *)
func funcWithMultipleShortFormAnnotationsForDifferentPlatforms() {
let _ = ClassWithShortFormAvailableOn10_51()
}
@available(OSX 10.51, *)
@available(OSX 10.53, *)
@available(OSX 10.52, *)
func funcWithMultipleShortFormAnnotationsForTheSamePlatform() {
let _ = ClassWithShortFormAvailableOn10_53()
let _ = ClassWithShortFormAvailableOn10_54() // expected-error {{'ClassWithShortFormAvailableOn10_54' is only available on OS X 10.54 or newer}}
// expected-note@-1 {{add 'if #available' version check}}
}
@available(OSX 10.9, *)
@available(OSX, unavailable)
func unavailableWins() { } // expected-note {{'unavailableWins()' has been explicitly marked unavailable here}}
func useShortFormAvailable() {
funcWithShortFormAvailableOn10_9()
funcWithShortFormAvailableOn10_51() // expected-error {{'funcWithShortFormAvailableOn10_51()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
funcWithShortFormAvailableOniOS14()
funcWithShortFormAvailableOniOS14AndOSX10_53() // expected-error {{'funcWithShortFormAvailableOniOS14AndOSX10_53()' is only available on OS X 10.53 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
funcWithMultipleShortFormAnnotationsForDifferentPlatforms() // expected-error {{'funcWithMultipleShortFormAnnotationsForDifferentPlatforms()' is only available on OS X 10.51 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
funcWithMultipleShortFormAnnotationsForTheSamePlatform() // expected-error {{'funcWithMultipleShortFormAnnotationsForTheSamePlatform()' is only available on OS X 10.53 or newer}}
// expected-note@-1 {{add @available attribute to enclosing global function}}
// expected-note@-2 {{add 'if #available' version check}}
// CHECK:error: 'unavailableWins()' is unavailable
unavailableWins() // expected-error {{'unavailableWins()' is unavailable}}
}
| apache-2.0 | 4068624e86eaeb8194c9d991f3446e19 | 44.27546 | 355 | 0.705118 | 3.805053 | false | false | false | false |
ArnavChawla/InteliChat | Carthage/Checkouts/swift-sdk/Source/ConversationV1/Models/RuntimeIntent.swift | 2 | 2629 | /**
* Copyright IBM Corporation 2018
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/** An intent identified in the user input. */
public struct RuntimeIntent: Codable {
/// The name of the recognized intent.
public var intent: String
/// A decimal percentage that represents Watson's confidence in the intent.
public var confidence: Double
/// Additional properties associated with this model.
public var additionalProperties: [String: JSON]
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case intent = "intent"
case confidence = "confidence"
static let allValues = [intent, confidence]
}
/**
Initialize a `RuntimeIntent` with member variables.
- parameter intent: The name of the recognized intent.
- parameter confidence: A decimal percentage that represents Watson's confidence in the intent.
- returns: An initialized `RuntimeIntent`.
*/
public init(intent: String, confidence: Double, additionalProperties: [String: JSON] = [:]) {
self.intent = intent
self.confidence = confidence
self.additionalProperties = additionalProperties
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
intent = try container.decode(String.self, forKey: .intent)
confidence = try container.decode(Double.self, forKey: .confidence)
let dynamicContainer = try decoder.container(keyedBy: DynamicKeys.self)
additionalProperties = try dynamicContainer.decode([String: JSON].self, excluding: CodingKeys.allValues)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(intent, forKey: .intent)
try container.encode(confidence, forKey: .confidence)
var dynamicContainer = encoder.container(keyedBy: DynamicKeys.self)
try dynamicContainer.encodeIfPresent(additionalProperties)
}
}
| mit | 30721af8787ddca05f9f4fafe338d336 | 37.661765 | 112 | 0.711677 | 4.788707 | false | false | false | false |
KrishMunot/swift | validation-test/StdlibUnittest/Common.swift | 1 | 18177 | // RUN: %target-run-simple-swift | FileCheck %s
// REQUIRES: executable_test
import SwiftPrivate
import StdlibUnittest
_setOverrideOSVersion(.osx(major: 10, minor: 9, bugFix: 3))
_setTestSuiteFailedCallback() { print("abort()") }
//
// Test that harness aborts when a test fails
//
var TestSuitePasses = TestSuite("TestSuitePasses")
// CHECK: {{^}}[ RUN ] TestSuitePasses.passes{{$}}
// CHECK: {{^}}[ OK ] TestSuitePasses.passes{{$}}
TestSuitePasses.test("passes") {
expectEqual(1, 1)
}
// CHECK: {{^}}[ RUN ] TestSuitePasses.passes/parameterized/0{{$}}
// CHECK: {{^}}stdout>>> 1010{{$}}
// CHECK: {{^}}[ OK ] TestSuitePasses.passes/parameterized/0{{$}}
// CHECK: {{^}}[ RUN ] TestSuitePasses.passes/parameterized/1{{$}}
// CHECK: {{^}}stdout>>> 2020{{$}}
// CHECK: {{^}}[ OK ] TestSuitePasses.passes/parameterized/1{{$}}
TestSuitePasses.test("passes/parameterized").forEach(in: [1010, 2020]) {
(parameter) in
print(parameter)
expectEqual(1, 1)
}
// CHECK: TestSuitePasses: All tests passed
var TestSuiteUXPasses = TestSuite("TestSuiteUXPasses")
// CHECK: {{^}}[ UXPASS ] TestSuiteUXPasses.uxpasses{{$}}
TestSuiteUXPasses.test("uxpasses").xfail(.osxAny("")).code {
expectEqual(1, 1)
}
// CHECK: {{^}}[ UXPASS ] TestSuiteUXPasses.uxpasses/parameterized/0{{$}}
// CHECK: {{^}}[ XFAIL ] TestSuiteUXPasses.uxpasses/parameterized/1{{$}}
TestSuiteUXPasses.test("uxpasses/parameterized")
.xfail(.osxAny(""))
.forEach(in: [1010, 2020]) {
(parameter) in
if parameter == 1010 {
expectEqual(1, 1)
} else {
expectEqual(1, 2)
}
}
// CHECK: TestSuiteUXPasses: Some tests failed, aborting
// CHECK: UXPASS: ["uxpasses", "uxpasses/parameterized/0"]
// CHECK: FAIL: []
// CHECK: SKIP: []
// CHECK: abort()
var TestSuiteFails = TestSuite("TestSuiteFails")
// CHECK: {{^}}[ FAIL ] TestSuiteFails.fails{{$}}
TestSuiteFails.test("fails") {
expectEqual(1, 2)
}
// CHECK: {{^}}[ OK ] TestSuiteFails.fails/parameterized/0{{$}}
// CHECK: {{^}}[ FAIL ] TestSuiteFails.fails/parameterized/1{{$}}
TestSuiteFails.test("fails/parameterized").forEach(in: [1010, 2020]) {
(parameter) in
if parameter == 1010 {
expectEqual(1, 1)
} else {
expectEqual(1, 2)
}
}
// CHECK: TestSuiteFails: Some tests failed, aborting
// CHECK: UXPASS: []
// CHECK: FAIL: ["fails", "fails/parameterized/1"]
// CHECK: SKIP: []
// CHECK: abort()
var TestSuiteXFails = TestSuite("TestSuiteXFails")
// CHECK: {{^}}[ XFAIL ] TestSuiteXFails.xfails{{$}}
TestSuiteXFails.test("xfails").xfail(.osxAny("")).code {
expectEqual(1, 2)
}
// CHECK: {{^}}[ UXPASS ] TestSuiteXFails.xfails/parameterized/0{{$}}
// CHECK: {{^}}[ XFAIL ] TestSuiteXFails.xfails/parameterized/1{{$}}
TestSuiteXFails.test("xfails/parameterized")
.xfail(.osxAny(""))
.forEach(in: [1010, 2020]) {
(parameter) in
if parameter == 1010 {
expectEqual(1, 1)
} else {
expectEqual(1, 2)
}
}
// CHECK: TestSuiteXFails: Some tests failed, aborting
// CHECK: UXPASS: ["xfails/parameterized/0"]
// CHECK: FAIL: []
// CHECK: SKIP: []
//
// Test 'xfail:' and 'skip:' annotations
//
var XFailsAndSkips = TestSuite("XFailsAndSkips")
// CHECK: [ OK ] XFailsAndSkips.passes{{$}}
XFailsAndSkips.test("passes") {
expectEqual(1, 1)
}
// CHECK: [ FAIL ] XFailsAndSkips.fails{{$}}
XFailsAndSkips.test("fails") {
expectEqual(1, 2)
}
// CHECK: [ XFAIL ] XFailsAndSkips.fails-always{{$}}
XFailsAndSkips.test("fails-always")
.xfail(.always("must always fail")).code {
expectEqual(1, 2)
}
// CHECK: [ OK ] XFailsAndSkips.fails-never{{$}}
XFailsAndSkips.test("fails-never")
.xfail(.never).code {
expectEqual(1, 1)
}
// CHECK: [ XFAIL ] XFailsAndSkips.xfail 10.9.3 passes{{$}}
XFailsAndSkips.test("xfail 10.9.3 passes")
.xfail(.osxBugFix(10, 9, 3, reason: "")).code {
expectEqual(1, 2)
}
// CHECK: [ XFAIL ] XFailsAndSkips.xfail 10.9.3 fails{{$}}
XFailsAndSkips.test("xfail 10.9.3 fails")
.xfail(.osxBugFix(10, 9, 3, reason: "")).code {
expectEqual(1, 2)
}
// CHECK: [ SKIP ] XFailsAndSkips.skipAlways (skip: [Always(reason: skip)]){{$}}
XFailsAndSkips.test("skipAlways")
.skip(.always("skip")).code {
fatalError("should not happen")
}
// CHECK: [ OK ] XFailsAndSkips.skipNever{{$}}
XFailsAndSkips.test("skipNever")
.skip(.never).code {
expectEqual(1, 1)
}
// CHECK: [ FAIL ] XFailsAndSkips.skip 10.9.2 passes{{$}}
XFailsAndSkips.test("skip 10.9.2 passes")
.skip(.osxBugFix(10, 9, 2, reason: "")).code {
expectEqual(1, 2)
}
// CHECK: [ FAIL ] XFailsAndSkips.skip 10.9.2 fails{{$}}
XFailsAndSkips.test("skip 10.9.2 fails")
.skip(.osxBugFix(10, 9, 2, reason: "")).code {
expectEqual(1, 2)
}
// CHECK: [ SKIP ] XFailsAndSkips.skip 10.9.3 (skip: [osx(10.9.3, reason: )]){{$}}
XFailsAndSkips.test("skip 10.9.3")
.skip(.osxBugFix(10, 9, 3, reason: "")).code {
expectEqual(1, 2)
fatalError("should not be executed")
}
// CHECK: XFailsAndSkips: Some tests failed, aborting
// CHECK: abort()
//
// Test custom XFAIL predicates
//
var XFailsCustomPredicates = TestSuite("XFailsCustomPredicates")
// CHECK: [ XFAIL ] XFailsCustomPredicates.matches{{$}}
XFailsCustomPredicates.test("matches")
.xfail(.custom({ true }, reason: "")).code {
expectEqual(1, 2)
}
// CHECK: [ OK ] XFailsCustomPredicates.not matches{{$}}
XFailsCustomPredicates.test("not matches")
.xfail(.custom({ false }, reason: "")).code {
expectEqual(1, 1)
}
// CHECK: XFailsCustomPredicates: All tests passed
//
// Test version comparison rules
//
var XFailsOSX = TestSuite("XFailsOSX")
// CHECK: [ UXPASS ] XFailsOSX.xfail OSX passes{{$}}
XFailsOSX.test("xfail OSX passes").xfail(.osxAny("")).code {
expectEqual(1, 1)
}
// CHECK: [ XFAIL ] XFailsOSX.xfail OSX fails{{$}}
XFailsOSX.test("xfail OSX fails").xfail(.osxAny("")).code {
expectEqual(1, 2)
}
// CHECK: [ OK ] XFailsOSX.xfail 9.*{{$}}
XFailsOSX.test("xfail 9.*").xfail(.osxMajor(9, reason: "")).code {
expectEqual(1, 1)
}
// CHECK: [ XFAIL ] XFailsOSX.xfail 10.*{{$}}
XFailsOSX.test("xfail 10.*").xfail(.osxMajor(10, reason: "")).code {
expectEqual(1, 2)
}
// CHECK: [ OK ] XFailsOSX.xfail 10.8{{$}}
XFailsOSX.test("xfail 10.8").xfail(.osxMinor(10, 8, reason: "")).code {
expectEqual(1, 1)
}
// CHECK: [ XFAIL ] XFailsOSX.xfail 10.9{{$}}
XFailsOSX.test("xfail 10.9").xfail(.osxMinor(10, 9, reason: "")).code {
expectEqual(1, 2)
}
// CHECK: [ OK ] XFailsOSX.xfail 10.[7-8]{{$}}
XFailsOSX.test("xfail 10.[7-8]")
.xfail(.osxMinorRange(10, 7...8, reason: "")).code {
expectEqual(1, 1)
}
// CHECK: [ XFAIL ] XFailsOSX.xfail 10.[9-10]{{$}}
XFailsOSX.test("xfail 10.[9-10]")
.xfail(.osxMinorRange(10, 9...10, reason: "")).code {
expectEqual(1, 2)
}
// CHECK: [ OK ] XFailsOSX.xfail 10.9.2{{$}}
XFailsOSX.test("xfail 10.9.2")
.xfail(.osxBugFix(10, 9, 2, reason: "")).code {
expectEqual(1, 1)
}
// CHECK: [ XFAIL ] XFailsOSX.xfail 10.9.3{{$}}
XFailsOSX.test("xfail 10.9.3")
.xfail(.osxBugFix(10, 9, 3, reason: "")).code {
expectEqual(1, 2)
}
// CHECK: [ OK ] XFailsOSX.xfail 10.9.[1-2]{{$}}
XFailsOSX.test("xfail 10.9.[1-2]")
.xfail(.osxBugFixRange(10, 9, 1...2, reason: "")).code {
expectEqual(1, 1)
}
// CHECK: [ XFAIL ] XFailsOSX.xfail 10.9.[3-4]{{$}}
XFailsOSX.test("xfail 10.9.[3-4]")
.xfail(.osxBugFixRange(10, 9, 3...4, reason: "")).code {
expectEqual(1, 2)
}
// CHECK: XFailsOSX: Some tests failed, aborting
// CHECK: abort()
//
// Check that we pass through stdout and stderr
//
var PassThroughStdoutStderr = TestSuite("PassThroughStdoutStderr")
PassThroughStdoutStderr.test("hasNewline") {
print("stdout first")
print("stdout second")
print("stdout third")
var stderr = _Stderr()
print("stderr first", to: &stderr)
print("stderr second", to: &stderr)
print("stderr third", to: &stderr)
}
// CHECK: [ RUN ] PassThroughStdoutStderr.hasNewline
// CHECK-DAG: stdout>>> stdout first
// CHECK-DAG: stdout>>> stdout second
// CHECK-DAG: stdout>>> stdout third
// CHECK-DAG: stderr>>> stderr first
// CHECK-DAG: stderr>>> stderr second
// CHECK-DAG: stderr>>> stderr third
// CHECK: [ OK ] PassThroughStdoutStderr.hasNewline
PassThroughStdoutStderr.test("noNewline") {
print("stdout first")
print("stdout second")
print("stdout third", terminator: "")
var stderr = _Stderr()
print("stderr first", to: &stderr)
print("stderr second", to: &stderr)
print("stderr third", terminator: "", to: &stderr)
}
// CHECK: [ RUN ] PassThroughStdoutStderr.noNewline
// CHECK-DAG: stdout>>> stdout first
// CHECK-DAG: stdout>>> stdout second
// CHECK-DAG: stdout>>> stdout third
// CHECK-DAG: stderr>>> stderr first
// CHECK-DAG: stderr>>> stderr second
// CHECK-DAG: stderr>>> stderr third
// CHECK: [ OK ] PassThroughStdoutStderr.noNewline
// CHECK: PassThroughStdoutStderr: All tests passed
//
// Test 'setUp' and 'tearDown'
//
var TestSuiteWithSetUp = TestSuite("TestSuiteWithSetUp")
var TestSuiteWithSetUpTimesCalled = 0
TestSuiteWithSetUp.setUp {
print("setUp")
if TestSuiteWithSetUpTimesCalled == 1 || TestSuiteWithSetUpTimesCalled == 3 {
expectEqual(1, 2)
}
TestSuiteWithSetUpTimesCalled += 1
}
// CHECK: [ RUN ] TestSuiteWithSetUp.passes
// CHECK: stdout>>> setUp
// CHECK: stdout>>> test body
// CHECK: [ OK ] TestSuiteWithSetUp.passes
TestSuiteWithSetUp.test("passes") {
print("test body")
}
// CHECK: [ RUN ] TestSuiteWithSetUp.fails
// CHECK: stdout>>> setUp
// CHECK-NEXT: stdout>>> check failed at {{.*}}/StdlibUnittest/Common.swift, line
// CHECK: stdout>>> test body
// CHECK: [ FAIL ] TestSuiteWithSetUp.fails
TestSuiteWithSetUp.test("fails") {
print("test body")
}
// CHECK: [ RUN ] TestSuiteWithSetUp.passesFails/parameterized/0
// CHECK: stdout>>> setUp
// CHECK: stdout>>> test body
// CHECK: [ OK ] TestSuiteWithSetUp.passesFails/parameterized/0
// CHECK: [ RUN ] TestSuiteWithSetUp.passesFails/parameterized/1
// CHECK: stdout>>> setUp
// CHECK-NEXT: stdout>>> check failed at {{.*}}/StdlibUnittest/Common.swift, line
// CHECK: stdout>>> test body
// CHECK: [ FAIL ] TestSuiteWithSetUp.passesFails/parameterized/1
TestSuiteWithSetUp.test("passesFails/parameterized")
.forEach(in: [1010, 2020]) {
(parameter) in
print("test body")
}
var TestSuiteWithTearDown = TestSuite("TestSuiteWithTearDown")
var TestSuiteWithTearDownShouldFail = false
TestSuiteWithTearDown.tearDown {
print("tearDown")
if TestSuiteWithTearDownShouldFail {
expectEqual(1, 2)
TestSuiteWithTearDownShouldFail = false
}
}
// CHECK: [ RUN ] TestSuiteWithTearDown.passes
// CHECK: stdout>>> test body
// CHECK: stdout>>> tearDown
// CHECK: [ OK ] TestSuiteWithTearDown.passes
TestSuiteWithTearDown.test("passes") {
print("test body")
}
// CHECK: [ RUN ] TestSuiteWithTearDown.fails
// CHECK: stdout>>> test body
// CHECK: stdout>>> tearDown
// CHECK-NEXT: stdout>>> check failed at {{.*}}/StdlibUnittest/Common.swift, line
// CHECK: [ FAIL ] TestSuiteWithTearDown.fails
TestSuiteWithTearDown.test("fails") {
print("test body")
TestSuiteWithTearDownShouldFail = true
}
// CHECK: [ RUN ] TestSuiteWithTearDown.passesFails/parameterized/0
// CHECK: stdout>>> test body
// CHECK: stdout>>> tearDown
// CHECK: [ OK ] TestSuiteWithTearDown.passesFails/parameterized/0
// CHECK: [ RUN ] TestSuiteWithTearDown.passesFails/parameterized/1
// CHECK: stdout>>> test body
// CHECK: stdout>>> tearDown
// CHECK-NEXT: stdout>>> check failed at {{.*}}/StdlibUnittest/Common.swift, line
// CHECK: [ FAIL ] TestSuiteWithTearDown.passesFails/parameterized/1
TestSuiteWithTearDown.test("passesFails/parameterized")
.forEach(in: [1010, 2020]) {
(parameter) in
print("test body")
if parameter != 1010 {
TestSuiteWithTearDownShouldFail = true
}
}
//
// Test assertions
//
var AssertionsTestSuite = TestSuite("Assertions")
AssertionsTestSuite.test("expectFailure/Pass") {
expectFailure {
expectEqual(1, 2)
return ()
}
}
// CHECK: [ RUN ] Assertions.expectFailure/Pass
// CHECK-NEXT: stdout>>> check failed at {{.*}}/StdlibUnittest/Common.swift, line
// CHECK: stdout>>> expected: 1 (of type Swift.Int)
// CHECK: stdout>>> actual: 2 (of type Swift.Int)
// CHECK: [ OK ] Assertions.expectFailure/Pass
AssertionsTestSuite.test("expectFailure/UXPass")
.xfail(.custom({ true }, reason: "test"))
.code {
expectFailure {
expectEqual(1, 2)
return ()
}
}
// CHECK: [ RUN ] Assertions.expectFailure/UXPass ({{X}}FAIL: [Custom(reason: test)])
// CHECK-NEXT: stdout>>> check failed at {{.*}}/StdlibUnittest/Common.swift, line
// CHECK: stdout>>> expected: 1 (of type Swift.Int)
// CHECK: stdout>>> actual: 2 (of type Swift.Int)
// CHECK: [ UXPASS ] Assertions.expectFailure/UXPass
AssertionsTestSuite.test("expectFailure/Fail") {
expectFailure {
return ()
}
}
// CHECK: [ RUN ] Assertions.expectFailure/Fail
// CHECK-NEXT: stdout>>> check failed at {{.*}}/StdlibUnittest/Common.swift, line
// CHECK: stdout>>> expected: true
// CHECK: stdout>>> running `body` should produce an expected failure
// CHECK: [ FAIL ] Assertions.expectFailure/Fail
AssertionsTestSuite.test("expectFailure/XFail")
.xfail(.custom({ true }, reason: "test"))
.code {
expectFailure {
return ()
}
}
// CHECK: [ RUN ] Assertions.expectFailure/XFail ({{X}}FAIL: [Custom(reason: test)])
// CHECK-NEXT: stdout>>> check failed at {{.*}}/StdlibUnittest/Common.swift, line
// CHECK: stdout>>> expected: true
// CHECK: stdout>>> running `body` should produce an expected failure
// CHECK: [ XFAIL ] Assertions.expectFailure/XFail
AssertionsTestSuite.test("expectFailure/AfterFailure/Fail") {
expectEqual(1, 2)
expectFailure {
expectEqual(3, 4)
return ()
}
}
// CHECK: [ RUN ] Assertions.expectFailure/AfterFailure/Fail
// CHECK-NEXT: stdout>>> check failed at {{.*}}/StdlibUnittest/Common.swift, line
// CHECK: stdout>>> expected: 1 (of type Swift.Int)
// CHECK: stdout>>> actual: 2 (of type Swift.Int)
// CHECK: stdout>>> check failed at {{.*}}/StdlibUnittest/Common.swift, line
// CHECK: stdout>>> expected: 3 (of type Swift.Int)
// CHECK: stdout>>> actual: 4 (of type Swift.Int)
// CHECK: [ FAIL ] Assertions.expectFailure/AfterFailure/Fail
AssertionsTestSuite.test("expectFailure/AfterFailure/XFail")
.xfail(.custom({ true }, reason: "test"))
.code {
expectEqual(1, 2)
expectFailure {
expectEqual(3, 4)
return ()
}
}
// CHECK: [ RUN ] Assertions.expectFailure/AfterFailure/XFail ({{X}}FAIL: [Custom(reason: test)])
// CHECK-NEXT: stdout>>> check failed at {{.*}}/StdlibUnittest/Common.swift, line
// CHECK: stdout>>> expected: 1 (of type Swift.Int)
// CHECK: stdout>>> actual: 2 (of type Swift.Int)
// CHECK: stdout>>> check failed at {{.*}}/StdlibUnittest/Common.swift, line
// CHECK: stdout>>> expected: 3 (of type Swift.Int)
// CHECK: stdout>>> actual: 4 (of type Swift.Int)
// CHECK: [ XFAIL ] Assertions.expectFailure/AfterFailure/XFail
AssertionsTestSuite.test("expectUnreachable") {
expectUnreachable()
}
// CHECK: [ RUN ] Assertions.expectUnreachable
// CHECK-NEXT: stdout>>> check failed at {{.*}}/StdlibUnittest/Common.swift, line
// CHECK: stdout>>> this code should not be executed
// CHECK: [ FAIL ] Assertions.expectUnreachable
AssertionsTestSuite.test("expectCrashLater/Pass") {
let array: [Int] = _opaqueIdentity([])
expectCrashLater()
_blackHole(array[0])
}
// CHECK: [ RUN ] Assertions.expectCrashLater/Pass
// CHECK: stderr>>> OK: saw expected "crashed: sig{{.*}}
// CHECK: [ OK ] Assertions.expectCrashLater/Pass
AssertionsTestSuite.test("expectCrashLater/UXPass")
.xfail(.custom({ true }, reason: "test"))
.code {
let array: [Int] = _opaqueIdentity([])
expectCrashLater()
_blackHole(array[0])
}
// CHECK: [ RUN ] Assertions.expectCrashLater/UXPass ({{X}}FAIL: [Custom(reason: test)])
// CHECK: stderr>>> OK: saw expected "crashed: sig{{.*}}
// CHECK: [ UXPASS ] Assertions.expectCrashLater/UXPass
AssertionsTestSuite.test("expectCrashLater/Fail") {
expectCrashLater()
}
// CHECK: [ RUN ] Assertions.expectCrashLater/Fail
// CHECK: expecting a crash, but the test did not crash
// CHECK: [ FAIL ] Assertions.expectCrashLater/Fail
AssertionsTestSuite.test("expectCrashLater/XFail")
.xfail(.custom({ true }, reason: "test"))
.code {
expectCrashLater()
}
// CHECK: [ RUN ] Assertions.expectCrashLater/XFail ({{X}}FAIL: [Custom(reason: test)])
// CHECK: expecting a crash, but the test did not crash
// CHECK: [ XFAIL ] Assertions.expectCrashLater/XFail
AssertionsTestSuite.test("UnexpectedCrash/RuntimeTrap") {
let array: [Int] = _opaqueIdentity([])
_blackHole(array[0])
}
// CHECK: [ RUN ] Assertions.UnexpectedCrash/RuntimeTrap
// CHECK: stderr>>> CRASHED: SIG
// CHECK: the test crashed unexpectedly
// CHECK: [ FAIL ] Assertions.UnexpectedCrash/RuntimeTrap
AssertionsTestSuite.test("UnexpectedCrash/NullPointerDereference") {
let ptr: UnsafePointer<Int> = _opaqueIdentity(nil)
_blackHole(ptr.pointee)
}
// CHECK: [ RUN ] Assertions.UnexpectedCrash/NullPointerDereference
// CHECK: stderr>>> CRASHED: SIG
// CHECK: the test crashed unexpectedly
// CHECK: [ FAIL ] Assertions.UnexpectedCrash/NullPointerDereference
var TestSuiteLifetimeTracked = TestSuite("TestSuiteLifetimeTracked")
var leakMe: LifetimeTracked? = nil
TestSuiteLifetimeTracked.test("failsIfLifetimeTrackedAreLeaked") {
leakMe = LifetimeTracked(0)
}
// CHECK: [ RUN ] TestSuiteLifetimeTracked.failsIfLifetimeTrackedAreLeaked
// CHECK-NEXT: stdout>>> check failed at {{.*}}.swift, line [[@LINE-4]]
// CHECK: stdout>>> expected: 0 (of type Swift.Int)
// CHECK: stdout>>> actual: 1 (of type Swift.Int)
// CHECK: [ FAIL ] TestSuiteLifetimeTracked.failsIfLifetimeTrackedAreLeaked
TestSuiteLifetimeTracked.test("passesIfLifetimeTrackedAreResetAfterFailure") {}
// CHECK: [ RUN ] TestSuiteLifetimeTracked.passesIfLifetimeTrackedAreResetAfterFailure
// CHECK: [ OK ] TestSuiteLifetimeTracked.passesIfLifetimeTrackedAreResetAfterFailure
runAllTests()
| apache-2.0 | 9bc40931bb3c1f52ce976c7149d0b111 | 29.652614 | 102 | 0.670243 | 3.744747 | false | true | false | false |
spire-inc/JustLog | JustLog/Classes/ConsoleDestination.swift | 1 | 1468 | //
// ConsoleDestination.swift
// JustLog
//
// Created by Alberto De Bortoli on 06/12/2016.
// Copyright © 2017 Just Eat. All rights reserved.
//
import Foundation
import SwiftyBeaver
import os.log
public class ConsoleDestination: BaseDestination {
public override init() {
super.init()
levelColor.verbose = "📣"
levelColor.debug = "📝"
levelColor.info = "ℹ️"
levelColor.warning = "⚠️"
levelColor.error = "☠️"
levelString.verbose = ""
levelString.debug = ""
levelString.info = ""
levelString.warning = ""
levelString.error = ""
}
override public func send(_ level: SwiftyBeaver.Level, msg: String, thread: String,
file: String, function: String, line: Int, context: Any?) -> String? {
var dict = msg.toDictionary()
guard var innerMessage = dict?["message"] as? String else { return nil }
if let userInfo = dict?["userInfo"] as? Dictionary<String, Any> {
if let queueLabel = userInfo["queue_label"] as? String {
innerMessage = "(\(queueLabel)) " + innerMessage
}
}
let formattedString = super.send(level, msg: innerMessage, thread: thread, file: file, function: function, line: line, context: context)
if let str = formattedString {
os_log("%{public}@", str)
}
return formattedString
}
}
| apache-2.0 | d42ead7a8c115c580ba58525c6b8714b | 27.411765 | 144 | 0.586611 | 4.431193 | false | false | false | false |
liuguya/TestKitchen_1606 | TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBRecommendLikeCell.swift | 1 | 3013 | //
// CBRecommendLikeCell.swift
// TestKitchen
//
// Created by 阳阳 on 16/8/17.
// Copyright © 2016年 liuguyang. All rights reserved.
//
import UIKit
class CBRecommendLikeCell: UITableViewCell {
@IBAction func clickBtn(sender: UIButton) {
print("1")
}
//显示数据
var model:CBRecommendWidgetListModel? {
didSet{
//显示图片和文字
showData()
}
}
func showData(){
for var i in 0..<8{
//图片
if model?.widget_data?.count > i{
let imageModel = model?.widget_data![i]
if imageModel?.type == "image"{
//获取图片视图
//tag: 200 201 202 203
let index = i/2
let subView = self.contentView.viewWithTag(200+index)
//判断类型
if (subView?.isKindOfClass(UIImageView.self)) == true{
let imageView = subView as! UIImageView
let url = NSURL(string: (imageModel?.content!)!)
let image = UIImage(named: "sdefaultImage")
imageView.kf_setImageWithURL(url, placeholderImage: image, optionsInfo: nil, progressBlock: nil, completionHandler: nil)
}
}
}
//文字
if model?.widget_data?.count > i+1{
let textModel = model?.widget_data![i+1]
if textModel?.type == "text"{
//tag 300 301 302 303
let subView = self.contentView.viewWithTag(300+i/2)
if (subView?.isKindOfClass(UILabel.self)) == true{
//print(textModel?.content!)
let label = subView as! UILabel
label.text = textModel?.content!
}
}
}
//每次遍历2个
i += 1
}
}
//创建cell的方法
class func createLikeCellFor(tableView:UITableView,atIndexPath indexPath:NSIndexPath,withlistModel listModel:CBRecommendWidgetListModel) -> CBRecommendLikeCell{
//猜你喜欢
let cellId = "recommendLikeCellId"
var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CBRecommendLikeCell
if cell == nil {
cell = NSBundle.mainBundle().loadNibNamed("CBRecommendLikeCell", owner: nil, options: nil).last as? CBRecommendLikeCell
}
cell?.model = listModel
return cell!
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| mit | 151ce3a7553cabd0db1a522b41cda290 | 29.821053 | 164 | 0.505123 | 5.256732 | false | false | false | false |
typarker/LotLizard | KitchenSink/LeftNavTableViewController.swift | 1 | 3391 | //
// LeftNavTableViewController.swift
// DrawerControllerKitchenSink
//
// Created by Ty Parker on 1/16/15.
// Copyright (c) 2015 evolved.io. All rights reserved.
//
import UIKit
class LeftNavTableViewController: UITableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return 2
}
/**
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellIdentifier = "Cell"
var cell: UITableViewCell! = tableView.dequeueReusableCellWithIdentifier(LeftNavTableViewCell) as? UITableViewCell
//cell.title.text = "gasg"
return cell
}*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
// Pass the selected object to the new view controller.
}
*/
}
| mit | efc67988e89fa759d8094a2c81305efd | 33.958763 | 157 | 0.683279 | 5.531811 | false | false | false | false |
andyshep/Palettes | Palettes/RemoteIncrementalStore.swift | 1 | 4632 | //
// RemoteIncrementalStore.swift
// Palettes
//
// Created by Andrew Shepard on 12/7/15.
// Copyright (c) 2015 Andrew Shepard. All rights reserved.
//
import CoreData
@objc(RemoteIncrementalStore)
final class RemoteIncrementalStore: NSIncrementalStore {
enum Error: Swift.Error {
case objectIDMissing
case cachedValuesMissing
case wrongObjectType
case wrongRequestType
case invalidResponse
case invalidJSON
case entityNotFound
case missingContext
}
private typealias CachedObjectValues = [String: Any]
/// The cache of managed object ids
private var cache: [NSManagedObjectID: CachedObjectValues] = [:]
class var storeType: String {
return String(describing: RemoteIncrementalStore.self)
}
// MARK: NSIncrementalStore overrides
override func loadMetadata() throws {
self.metadata = [
NSStoreTypeKey: RemoteIncrementalStore.storeType,
NSStoreUUIDKey: ProcessInfo.processInfo.globallyUniqueString
]
}
override func execute(_ request: NSPersistentStoreRequest, with context: NSManagedObjectContext?) throws -> Any {
guard request.requestType == .fetchRequestType else { throw Error.wrongRequestType }
return try executeFetchRequest(request, with: context)
}
override func newValuesForObject(with objectID: NSManagedObjectID, with context: NSManagedObjectContext) throws -> NSIncrementalStoreNode {
guard let values = cache[objectID] else { throw Error.cachedValuesMissing }
return NSIncrementalStoreNode(objectID: objectID, withValues: values, version: 1)
}
}
extension RemoteIncrementalStore {
private func objectIdForNewObject(entityDescription: NSEntityDescription, cacheValues: CachedObjectValues) -> NSManagedObjectID? {
guard let referenceID = cacheValues["id"] as? Int else { return nil }
let objectId = newObjectID(for: entityDescription, referenceObject: referenceID)
let extracted = Palette.extractAttributeValues(from: cacheValues)
cache[objectId] = extracted
return objectId
}
private func executeFetchRequest(_ request: NSPersistentStoreRequest, with context: NSManagedObjectContext?) throws -> Any {
guard let fetchRequest = request as? NSFetchRequest<NSManagedObject> else { throw Error.wrongRequestType }
guard let context = context else { throw Error.missingContext }
return try fetchRemoteObjects(matching: fetchRequest, with: context)
}
private func fetchRemoteObjects(matching request: NSFetchRequest<NSManagedObject>, with context: NSManagedObjectContext) throws -> [AnyObject] {
let offset = request.fetchOffset
let limit = request.fetchLimit
let httpRequest = ColourLovers.topPalettes.request(offset: offset, limit: limit)
let session = URLSession(configuration: URLSessionConfiguration.default)
guard let entity = request.entity else { throw Error.entityNotFound }
return try context.performAndWait { () throws -> [Palette] in
guard
let data = try session.sendSynchronousDataTask(request: httpRequest)
else { throw Error.invalidResponse }
guard
let results = try JSONSerialization.jsonObject(with: data, options: []) as? [CachedObjectValues]
else { throw Error.invalidJSON }
return try results.map { item -> Palette in
guard let objectId = objectIdForNewObject(entityDescription: entity, cacheValues: item) else {
throw Error.objectIDMissing
}
guard let palette = context.object(with: objectId) as? Palette else {
throw Error.wrongObjectType
}
return palette
}
}
}
}
// FIXME: refactor this away
extension URLSession {
func sendSynchronousDataTask(request: URLRequest) throws -> Data? {
let semaphore = DispatchSemaphore(value: 0)
var result: Data? = nil
var error: Error? = nil
let task = self.dataTask(with: request) { (data, response, err) -> Void in
result = data
error = err
semaphore.signal()
}
task.resume()
let _ = semaphore.wait(timeout: DispatchTime.distantFuture)
if let error = error {
throw error
}
return result
}
}
| mit | cbe3391bc3049919142a1629676bf4c1 | 36.056 | 148 | 0.648748 | 5.398601 | false | false | false | false |
alvinvarghese/Natalie | natalie.swift | 1 | 47749 | #!/usr/bin/env xcrun -sdk macosx swift
//
// Natalie - Storyboard Generator Script
//
// Generate swift file based on storyboard files
//
// Usage:
// natalie.swift Main.storyboard > Storyboards.swift
// natalie.swift path/toproject/with/storyboards > Storyboards.swift
//
// Licence: MIT
// Author: Marcin Krzyżanowski http://blog.krzyzanowskim.com
//
//MARK: SWXMLHash
//
// SWXMLHash.swift
//
// Copyright (c) 2014 David Mohundro
//
// 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
//MARK: Extensions
private extension String {
func trimAllWhitespacesAndSpecialCharacters() -> String {
let invalidCharacters = NSCharacterSet.alphanumericCharacterSet().invertedSet
let x = self.componentsSeparatedByCharactersInSet(invalidCharacters)
return x.joinWithSeparator("")
}
}
private func SwiftRepresentationForString(string: String, capitalizeFirstLetter: Bool = false) -> String {
var str = string.trimAllWhitespacesAndSpecialCharacters()
if capitalizeFirstLetter {
str = String(str.uppercaseString.unicodeScalars.prefix(1) + str.unicodeScalars.suffix(str.unicodeScalars.count - 1))
}
return str
}
//MARK: Parser
let rootElementName = "SWXMLHash_Root_Element"
/// Simple XML parser.
public class SWXMLHash {
/**
Method to parse XML passed in as a string.
- parameter xml: The XML to be parsed
- returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func parse(xml: String) -> XMLIndexer {
return parse((xml as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
}
/**
Method to parse XML passed in as an NSData instance.
- parameter xml: The XML to be parsed
- returns: An XMLIndexer instance that is used to look up elements in the XML
*/
class public func parse(data: NSData) -> XMLIndexer {
let parser = XMLParser()
return parser.parse(data)
}
class public func lazy(xml: String) -> XMLIndexer {
return lazy((xml as NSString).dataUsingEncoding(NSUTF8StringEncoding)!)
}
class public func lazy(data: NSData) -> XMLIndexer {
let parser = LazyXMLParser()
return parser.parse(data)
}
}
struct Stack<T> {
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
mutating func removeAll() {
items.removeAll(keepCapacity: false)
}
func top() -> T {
return items[items.count - 1]
}
}
class LazyXMLParser: NSObject, NSXMLParserDelegate {
override init() {
super.init()
}
var root = XMLElement(name: rootElementName)
var parentStack = Stack<XMLElement>()
var elementStack = Stack<String>()
var data: NSData?
var ops: [IndexOp] = []
func parse(data: NSData) -> XMLIndexer {
self.data = data
return XMLIndexer(self)
}
func startParsing(ops: [IndexOp]) {
// clear any prior runs of parse... expected that this won't be necessary, but you never know
parentStack.removeAll()
root = XMLElement(name: rootElementName)
parentStack.push(root)
self.ops = ops
let parser = NSXMLParser(data: data!)
parser.delegate = self
parser.parse()
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String]) {
elementStack.push(elementName)
if !onMatch() {
return
}
let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeDict)
parentStack.push(currentNode)
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
if !onMatch() {
return
}
let current = parentStack.top()
if current.text == nil {
current.text = ""
}
parentStack.top().text! += string
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
let match = onMatch()
elementStack.pop()
if match {
parentStack.pop()
}
}
func onMatch() -> Bool {
// we typically want to compare against the elementStack to see if it matches ops, *but*
// if we're on the first element, we'll instead compare the other direction.
if elementStack.items.count > ops.count {
return elementStack.items.startsWith(ops.map { $0.key })
}
else {
return ops.map { $0.key }.startsWith(elementStack.items)
}
}
}
/// The implementation of NSXMLParserDelegate and where the parsing actually happens.
class XMLParser: NSObject, NSXMLParserDelegate {
override init() {
super.init()
}
var root = XMLElement(name: rootElementName)
var parentStack = Stack<XMLElement>()
func parse(data: NSData) -> XMLIndexer {
// clear any prior runs of parse... expected that this won't be necessary, but you never know
parentStack.removeAll()
parentStack.push(root)
let parser = NSXMLParser(data: data)
parser.delegate = self
parser.parse()
return XMLIndexer(root)
}
func parser(parser: NSXMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String: String]) {
let currentNode = parentStack.top().addElement(elementName, withAttributes: attributeDict)
parentStack.push(currentNode)
}
func parser(parser: NSXMLParser, foundCharacters string: String) {
let current = parentStack.top()
if current.text == nil {
current.text = ""
}
parentStack.top().text! += string
}
func parser(parser: NSXMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
parentStack.pop()
}
}
public class IndexOp {
var index: Int
let key: String
init(_ key: String) {
self.key = key
self.index = -1
}
func toString() -> String {
if index >= 0 {
return key + " " + index.description
}
return key
}
}
public class IndexOps {
var ops: [IndexOp] = []
let parser: LazyXMLParser
init(parser: LazyXMLParser) {
self.parser = parser
}
func findElements() -> XMLIndexer {
parser.startParsing(ops)
let indexer = XMLIndexer(parser.root)
var childIndex = indexer
for op in ops {
childIndex = childIndex[op.key]
if op.index >= 0 {
childIndex = childIndex[op.index]
}
}
ops.removeAll(keepCapacity: false)
return childIndex
}
func stringify() -> String {
var s = ""
for op in ops {
s += "[" + op.toString() + "]"
}
return s
}
}
/// Returned from SWXMLHash, allows easy element lookup into XML data.
public enum XMLIndexer: SequenceType {
case Element(XMLElement)
case List([XMLElement])
case Stream(IndexOps)
case Error(NSError)
/// The underlying XMLElement at the currently indexed level of XML.
public var element: XMLElement? {
get {
switch self {
case .Element(let elem):
return elem
case .Stream(let ops):
let list = ops.findElements()
return list.element
default:
return nil
}
}
}
/// All elements at the currently indexed level
public var all: [XMLIndexer] {
get {
switch self {
case .List(let list):
var xmlList = [XMLIndexer]()
for elem in list {
xmlList.append(XMLIndexer(elem))
}
return xmlList
case .Element(let elem):
return [XMLIndexer(elem)]
case .Stream(let ops):
let list = ops.findElements()
return list.all
default:
return []
}
}
}
/// All child elements from the currently indexed level
public var children: [XMLIndexer] {
get {
var list = [XMLIndexer]()
for elem in all.map({ $0.element! }) {
for elem in elem.children {
list.append(XMLIndexer(elem))
}
}
return list
}
}
/**
Allows for element lookup by matching attribute values.
- parameter attr: should the name of the attribute to match on
- parameter _: should be the value of the attribute to match on
- returns: instance of XMLIndexer
*/
public func withAttr(attr: String, _ value: String) -> XMLIndexer {
let attrUserInfo = [NSLocalizedDescriptionKey: "XML Attribute Error: Missing attribute [\"\(attr)\"]"]
let valueUserInfo = [NSLocalizedDescriptionKey: "XML Attribute Error: Missing attribute [\"\(attr)\"] with value [\"\(value)\"]"]
switch self {
case .Stream(let opStream):
opStream.stringify()
let match = opStream.findElements()
return match.withAttr(attr, value)
case .List(let list):
if let elem = list.filter({ $0.attributes[attr] == value }).first {
return .Element(elem)
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: valueUserInfo))
case .Element(let elem):
if let attr = elem.attributes[attr] {
if attr == value {
return .Element(elem)
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: valueUserInfo))
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: attrUserInfo))
default:
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: attrUserInfo))
}
}
/**
Initializes the XMLIndexer
- parameter _: should be an instance of XMLElement, but supports other values for error handling
- returns: instance of XMLIndexer
*/
public init(_ rawObject: AnyObject) {
switch rawObject {
case let value as XMLElement:
self = .Element(value)
case let value as LazyXMLParser:
self = .Stream(IndexOps(parser: value))
default:
self = .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: nil))
}
}
/**
Find an XML element at the current level by element name
- parameter key: The element name to index by
- returns: instance of XMLIndexer to match the element (or elements) found by key
*/
public subscript(key: String) -> XMLIndexer {
get {
let userInfo = [NSLocalizedDescriptionKey: "XML Element Error: Incorrect key [\"\(key)\"]"]
switch self {
case .Stream(let opStream):
let op = IndexOp(key)
opStream.ops.append(op)
return .Stream(opStream)
case .Element(let elem):
let match = elem.children.filter({ $0.name == key })
if match.count > 0 {
if match.count == 1 {
return .Element(match[0])
}
else {
return .List(match)
}
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
default:
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
}
}
}
/**
Find an XML element by index within a list of XML Elements at the current level
- parameter index: The 0-based index to index by
- returns: instance of XMLIndexer to match the element (or elements) found by key
*/
public subscript(index: Int) -> XMLIndexer {
get {
let userInfo = [NSLocalizedDescriptionKey: "XML Element Error: Incorrect index [\"\(index)\"]"]
switch self {
case .Stream(let opStream):
opStream.ops[opStream.ops.count - 1].index = index
return .Stream(opStream)
case .List(let list):
if index <= list.count {
return .Element(list[index])
}
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
case .Element(let elem):
if index == 0 {
return .Element(elem)
}
else {
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
}
default:
return .Error(NSError(domain: "SWXMLDomain", code: 1000, userInfo: userInfo))
}
}
}
typealias GeneratorType = XMLIndexer
public func generate() -> IndexingGenerator<[XMLIndexer]> {
return all.generate()
}
}
/// XMLIndexer extensions
extension XMLIndexer: BooleanType {
/// True if a valid XMLIndexer, false if an error type
public var boolValue: Bool {
get {
switch self {
case .Error:
return false
default:
return true
}
}
}
}
extension XMLIndexer: CustomStringConvertible {
public var description: String {
get {
switch self {
case .List(let list):
return list.map { $0.description }.joinWithSeparator("\n")
case .Element(let elem):
if elem.name == rootElementName {
return elem.children.map { $0.description }.joinWithSeparator("\n")
}
return elem.description
default:
return ""
}
}
}
}
/// Models an XML element, including name, text and attributes
public class XMLElement {
/// The name of the element
public let name: String
/// The inner text of the element, if it exists
public var text: String?
/// The attributes of the element
public var attributes = [String:String]()
var children = [XMLElement]()
var count: Int = 0
var index: Int
/**
Initialize an XMLElement instance
- parameter name: The name of the element to be initialized
- returns: a new instance of XMLElement
*/
init(name: String, index: Int = 0) {
self.name = name
self.index = index
}
/**
Adds a new XMLElement underneath this instance of XMLElement
- parameter name: The name of the new element to be added
- parameter withAttributes: The attributes dictionary for the element being added
- returns: The XMLElement that has now been added
*/
func addElement(name: String, withAttributes attributes: NSDictionary) -> XMLElement {
let element = XMLElement(name: name, index: count)
count++
children.append(element)
for (keyAny,valueAny) in attributes {
let key = keyAny as! String
let value = valueAny as! String
element.attributes[key] = value
}
return element
}
}
extension XMLElement: CustomStringConvertible {
public var description:String {
get {
var attributesStringList = [String]()
if !attributes.isEmpty {
for (key, val) in attributes {
attributesStringList.append("\(key)=\"\(val)\"")
}
}
var attributesString = attributesStringList.joinWithSeparator(" ")
if (!attributesString.isEmpty) {
attributesString = " " + attributesString
}
if children.count > 0 {
var xmlReturn = [String]()
xmlReturn.append("<\(name)\(attributesString)>")
for child in children {
xmlReturn.append(child.description)
}
xmlReturn.append("</\(name)>")
return xmlReturn.joinWithSeparator("\n")
}
if text != nil {
return "<\(name)\(attributesString)>\(text!)</\(name)>"
} else {
return "<\(name)\(attributesString)/>"
}
}
}
}
//MARK: - Natalie
//MARK: Objects
enum OS: String, CustomStringConvertible {
case iOS = "iOS"
case OSX = "OSX"
static let allValues = [iOS, OSX]
enum Runtime: String {
case iOSCocoaTouch = "iOS.CocoaTouch"
case MacOSXCocoa = "MacOSX.Cocoa"
init(os: OS) {
switch os {
case iOS:
self = .iOSCocoaTouch
case OSX:
self = .MacOSXCocoa
}
}
}
enum Framework: String {
case UIKit = "UIKit"
case Cocoa = "Cocoa"
init(os: OS) {
switch os {
case iOS:
self = .UIKit
case OSX:
self = .Cocoa
}
}
}
init(targetRuntime: String) {
switch (targetRuntime) {
case Runtime.iOSCocoaTouch.rawValue:
self = .iOS
case Runtime.MacOSXCocoa.rawValue:
self = .OSX
case "iOS.CocoaTouch.iPad":
self = iOS
default:
fatalError("Unsupported")
}
}
var description: String {
return self.rawValue
}
var framework: String {
return Framework(os: self).rawValue
}
var targetRuntime: String {
return Runtime(os: self).rawValue
}
var storyboardType: String {
switch self {
case iOS:
return "UIStoryboard"
case OSX:
return "NSStoryboard"
}
}
var storyboardSegueType: String {
switch self {
case iOS:
return "UIStoryboardSegue"
case OSX:
return "NSStoryboardSegue"
}
}
var storyboardControllerTypes: [String] {
switch self {
case iOS:
return ["UIViewController"]
case OSX:
return ["NSViewController", "NSWindowController"]
}
}
var storyboardControllerSignatureType: String {
switch self {
case iOS:
return "ViewController"
case OSX:
return "Controller" // NSViewController or NSWindowController
}
}
var storyboardInstantiationInfo: [(String /* Signature type */, String /* Return type */)] {
switch self {
case iOS:
return [("ViewController", "UIViewController")]
case OSX:
return [("WindowController", "NSWindowController"), ("ViewController", "NSViewController")]
}
}
var viewType: String {
switch self {
case iOS:
return "UIView"
case OSX:
return "NSView"
}
}
var resuableViews: [String]? {
switch self {
case iOS:
return ["UICollectionReusableView", "UITableViewCell"]
case OSX:
return nil
}
}
var storyboardControllerReturnType: String {
switch self {
case iOS:
return "UIViewController"
case OSX:
return "AnyObject" // NSViewController or NSWindowController
}
}
func controllerTypeForElementName(name: String) -> String? {
switch self {
case iOS:
switch name {
case "viewController":
return "UIViewController"
case "navigationController":
return "UINavigationController"
case "tableViewController":
return "UITableViewController"
case "tabBarController":
return "UITabBarController"
case "splitViewController":
return "UISplitViewController"
case "pageViewController":
return "UIPageViewController"
case "collectionViewController":
return "UICollectionViewController"
case "exit":
return nil
default:
assertionFailure("Unknown controller element: \(name)")
return nil
}
case OSX:
switch name {
case "viewController":
return "NSViewController"
case "windowController":
return "NSWindowController"
case "pagecontroller":
return "NSPageController"
case "tabViewController":
return "NSTabViewController"
case "splitViewController":
return "NSSplitViewController"
case "exit":
return nil
default:
assertionFailure("Unknown controller element: \(name)")
return nil
}
}
}
}
class XMLObject {
let xml: XMLIndexer
let name: String
init(xml: XMLIndexer) {
self.xml = xml
self.name = xml.element!.name
}
func searchAll(attributeKey: String, attributeValue: String? = nil) -> [XMLIndexer]? {
return searchAll(self.xml, attributeKey: attributeKey, attributeValue: attributeValue)
}
func searchAll(root: XMLIndexer, attributeKey: String, attributeValue: String? = nil) -> [XMLIndexer]? {
var result = Array<XMLIndexer>()
for child in root.children {
for childAtLevel in child.all {
if let attributeValue = attributeValue {
if let element = childAtLevel.element where element.attributes[attributeKey] == attributeValue {
result += [childAtLevel]
}
} else if let element = childAtLevel.element where element.attributes[attributeKey] != nil {
result += [childAtLevel]
}
if let found = searchAll(childAtLevel, attributeKey: attributeKey, attributeValue: attributeValue) {
result += found
}
}
}
return result.count > 0 ? result : nil
}
func searchNamed(name: String) -> [XMLIndexer]? {
return self.searchNamed(self.xml, name: name)
}
func searchNamed(root: XMLIndexer, name: String) -> [XMLIndexer]? {
var result = Array<XMLIndexer>()
for child in root.children {
for childAtLevel in child.all {
if let elementName = childAtLevel.element?.name where elementName == name {
result += [child]
}
if let found = searchNamed(childAtLevel, name: name) {
result += found
}
}
}
return result.count > 0 ? result : nil
}
func searchById(id: String) -> XMLIndexer? {
return searchAll("id", attributeValue: id)?.first
}
}
class Scene: XMLObject {
lazy var viewController: ViewController? = {
if let vcs = self.searchAll("sceneMemberID", attributeValue: "viewController"), vc = vcs.first {
return ViewController(xml: vc)
}
return nil
}()
lazy var segues: [Segue]? = {
return self.searchNamed("segue")?.map { Segue(xml: $0) }
}()
lazy var customModule: String? = self.viewController?.customModule
lazy var customModuleProvider: String? = self.viewController?.customModuleProvider
}
class ViewController: XMLObject {
lazy var customClass: String? = self.xml.element?.attributes["customClass"]
lazy var customModuleProvider: String? = self.xml.element?.attributes["customModuleProvider"]
lazy var storyboardIdentifier: String? = self.xml.element?.attributes["storyboardIdentifier"]
lazy var customModule: String? = self.xml.element?.attributes["customModule"]
lazy var reusables: [Reusable]? = {
if let reusables = self.searchAll(self.xml, attributeKey: "reuseIdentifier"){
return reusables.map { Reusable(xml: $0) }
}
return nil
}()
}
class Segue: XMLObject {
let kind: String
let identifier: String?
lazy var destination: String? = self.xml.element?.attributes["destination"]
override init(xml: XMLIndexer) {
self.kind = xml.element!.attributes["kind"]!
if let id = xml.element?.attributes["identifier"] where id.characters.count > 0 {self.identifier = id}
else {self.identifier = nil}
super.init(xml: xml)
}
}
class Reusable: XMLObject {
let kind: String
lazy var reuseIdentifier: String? = self.xml.element?.attributes["reuseIdentifier"]
lazy var customClass: String? = self.xml.element?.attributes["customClass"]
override init(xml: XMLIndexer) {
kind = xml.element!.name
super.init(xml: xml)
}
}
class Storyboard: XMLObject {
let version: String
lazy var os:OS = {
guard let targetRuntime = self.xml["document"].element?.attributes["targetRuntime"] else {
return OS.iOS
}
return OS(targetRuntime: targetRuntime)
}()
lazy var initialViewControllerClass: String? = {
if let initialViewControllerId = self.xml["document"].element?.attributes["initialViewController"],
let xmlVC = self.searchById(initialViewControllerId)
{
let vc = ViewController(xml: xmlVC)
if let customClassName = vc.customClass {
return customClassName
}
if let controllerType = self.os.controllerTypeForElementName(vc.name) {
return controllerType
}
}
return nil
}()
lazy var scenes: [Scene] = {
guard let scenes = self.searchAll(self.xml, attributeKey: "sceneID") else {
return []
}
return scenes.map { Scene(xml: $0) }
}()
lazy var customModules: [String] = self.scenes.filter{ $0.customModule != nil && $0.customModuleProvider == nil }.map{ $0.customModule! }
override init(xml: XMLIndexer) {
self.version = xml["document"].element!.attributes["version"]!
super.init(xml: xml)
}
func processStoryboard(storyboardName: String, os: OS) {
print("")
print(" struct \(storyboardName) {")
print("")
print(" static let identifier = \"\(storyboardName)\"")
print("")
print(" static var storyboard: \(os.storyboardType) {")
print(" return \(os.storyboardType)(name: self.identifier, bundle: nil)")
print(" }")
if let initialViewControllerClass = self.initialViewControllerClass {
let cast = (initialViewControllerClass == os.storyboardControllerReturnType ? (os == OS.iOS ? "!" : "") : " as! \(initialViewControllerClass)")
print("")
print(" static func instantiateInitial\(os.storyboardControllerSignatureType)() -> \(initialViewControllerClass) {")
print(" return self.storyboard.instantiateInitial\(os.storyboardControllerSignatureType)()\(cast)")
print(" }")
}
for (signatureType, returnType) in os.storyboardInstantiationInfo {
let cast = (returnType == os.storyboardControllerReturnType ? "" : " as! \(returnType)")
print("")
print(" static func instantiate\(signatureType)WithIdentifier(identifier: String) -> \(returnType) {")
print(" return self.storyboard.instantiate\(os.storyboardControllerSignatureType)WithIdentifier(identifier)\(cast)")
print(" }")
}
for scene in self.scenes {
if let viewController = scene.viewController, storyboardIdentifier = viewController.storyboardIdentifier {
let controllerClass = (viewController.customClass ?? os.controllerTypeForElementName(viewController.name)!)
print("")
print(" static func instantiate\(SwiftRepresentationForString(storyboardIdentifier, capitalizeFirstLetter: true))() -> \(controllerClass) {")
print(" return self.storyboard.instantiate\(os.storyboardControllerSignatureType)WithIdentifier(\"\(storyboardIdentifier)\") as! \(controllerClass)")
print(" }")
}
}
print(" }")
}
func processViewControllers() {
for scene in self.scenes {
if let viewController = scene.viewController {
if let customClass = viewController.customClass {
print("")
print("//MARK: - \(customClass)")
if let segues = scene.segues?.filter({ return $0.identifier != nil })
where segues.count > 0 {
print("extension \(os.storyboardSegueType) {")
print(" func selection() -> \(customClass).Segue? {")
print(" if let identifier = self.identifier {")
print(" return \(customClass).Segue(rawValue: identifier)")
print(" }")
print(" return nil")
print(" }")
print("}")
print("")
}
if let segues = scene.segues?.filter({ return $0.identifier != nil })
where segues.count > 0 {
print("extension \(customClass) { ")
print("")
print(" enum Segue: String, CustomStringConvertible, SegueProtocol {")
for segue in segues {
if let identifier = segue.identifier
{
print(" case \(SwiftRepresentationForString(identifier)) = \"\(identifier)\"")
}
}
print("")
print(" var kind: SegueKind? {")
print(" switch (self) {")
var needDefaultSegue = false
for segue in segues {
if let identifier = segue.identifier {
print(" case \(SwiftRepresentationForString(identifier)):")
print(" return SegueKind(rawValue: \"\(segue.kind)\")")
} else {
needDefaultSegue = true
}
}
if needDefaultSegue {
print(" default:")
print(" assertionFailure(\"Invalid value\")")
print(" return nil")
}
print(" }")
print(" }")
print("")
print(" var destination: \(self.os.storyboardControllerReturnType).Type? {")
print(" switch (self) {")
var needDefaultDestination = false
for segue in segues {
if let identifier = segue.identifier, destination = segue.destination,
destinationElement = searchById(destination)?.element,
destinationClass = (destinationElement.attributes["customClass"] ?? os.controllerTypeForElementName(destinationElement.name))
{
print(" case \(SwiftRepresentationForString(identifier)):")
print(" return \(destinationClass).self")
} else {
needDefaultDestination = true
}
}
if needDefaultDestination {
print(" default:")
print(" assertionFailure(\"Unknown destination\")")
print(" return nil")
}
print(" }")
print(" }")
print("")
print(" var identifier: String? { return self.description } ")
print(" var description: String { return self.rawValue }")
print(" }")
print("")
print("}")
}
if let reusables = viewController.reusables?.filter({ return $0.reuseIdentifier != nil })
where reusables.count > 0 {
print("extension \(customClass) { ")
print("")
print(" enum Reusable: String, CustomStringConvertible, ReusableViewProtocol {")
for reusable in reusables {
if let identifier = reusable.reuseIdentifier {
print(" case \(identifier) = \"\(identifier)\"")
}
}
print("")
print(" var kind: ReusableKind? {")
print(" switch (self) {")
var needDefault = false
for reusable in reusables {
if let identifier = reusable.reuseIdentifier {
print(" case \(identifier):")
print(" return ReusableKind(rawValue: \"\(reusable.kind)\")")
} else {
needDefault = true
}
}
if needDefault {
print(" default:")
print(" preconditionFailure(\"Invalid value\")")
print(" break")
}
print(" }")
print(" }")
print("")
print(" var viewType: \(self.os.viewType).Type? {")
print(" switch (self) {")
needDefault = false
for reusable in reusables {
if let identifier = reusable.reuseIdentifier, customClass = reusable.customClass {
print(" case \(identifier):")
print(" return \(customClass).self")
} else {
needDefault = true
}
}
if needDefault {
print(" default:")
print(" return nil")
}
print(" }")
print(" }")
print("")
print(" var identifier: String? { return self.description } ")
print(" var description: String { return self.rawValue }")
print(" }")
print("")
print("}\n")
}
}
}
}
}
}
class StoryboardFile {
let data: NSData
let storyboardName: String
let storyboard: Storyboard
init(filePath: String) {
self.data = NSData(contentsOfFile: filePath)!
self.storyboardName = ((filePath as NSString).lastPathComponent as NSString).stringByDeletingPathExtension
self.storyboard = Storyboard(xml:SWXMLHash.parse(self.data))
}
}
//MARK: Functions
func findStoryboards(rootPath: String, suffix: String) -> [String]? {
var result = Array<String>()
let fm = NSFileManager.defaultManager()
if let paths = fm.subpathsAtPath(rootPath) {
let storyboardPaths = paths.filter({ return $0.hasSuffix(suffix)})
// result = storyboardPaths
for p in storyboardPaths {
result.append((rootPath as NSString).stringByAppendingPathComponent(p))
}
}
return result.count > 0 ? result : nil
}
func processStoryboards(storyboards: [StoryboardFile], os: OS) {
print("//")
print("// Autogenerated by Natalie - Storyboard Generator Script.")
print("// http://blog.krzyzanowskim.com")
print("//")
print("")
print("import \(os.framework)")
let modules = storyboards.flatMap{ $0.storyboard.customModules }
for module in Set<String>(modules) {
print("import \(module)")
}
print("")
print("//MARK: - Storyboards")
print("struct Storyboards {")
for file in storyboards {
file.storyboard.processStoryboard(file.storyboardName, os: os)
}
print("}")
print("")
print("//MARK: - ReusableKind")
print("enum ReusableKind: String, CustomStringConvertible {")
print(" case TableViewCell = \"tableViewCell\"")
print(" case CollectionViewCell = \"collectionViewCell\"")
print("")
print(" var description: String { return self.rawValue }")
print("}")
print("")
print("//MARK: - SegueKind")
print("enum SegueKind: String, CustomStringConvertible { ")
print(" case Relationship = \"relationship\" ")
print(" case Show = \"show\" ")
print(" case Presentation = \"presentation\" ")
print(" case Embed = \"embed\" ")
print(" case Unwind = \"unwind\" ")
print(" case Push = \"push\" ")
print(" case Modal = \"modal\" ")
print(" case Popover = \"popover\" ")
print(" case Replace = \"replace\" ")
print(" case Custom = \"custom\" ")
print("")
print(" var description: String { return self.rawValue } ")
print("}")
print("")
print("//MARK: - SegueProtocol")
print("public protocol IdentifiableProtocol: Equatable {")
print(" var identifier: String? { get }")
print("}")
print("")
print("public protocol SegueProtocol: IdentifiableProtocol {")
print("}")
print("")
print("public func ==<T: SegueProtocol, U: SegueProtocol>(lhs: T, rhs: U) -> Bool {")
print(" return lhs.identifier == rhs.identifier")
print("}")
print("")
print("public func ~=<T: SegueProtocol, U: SegueProtocol>(lhs: T, rhs: U) -> Bool {")
print(" return lhs.identifier == rhs.identifier")
print("}")
print("")
print("public func ==<T: SegueProtocol>(lhs: T, rhs: String) -> Bool {")
print(" return lhs.identifier == rhs")
print("}")
print("")
print("public func ~=<T: SegueProtocol>(lhs: T, rhs: String) -> Bool {")
print(" return lhs.identifier == rhs")
print("}")
print("")
print("public func ==<T: SegueProtocol>(lhs: String, rhs: T) -> Bool {")
print(" return lhs == rhs.identifier")
print("}")
print("")
print("public func ~=<T: SegueProtocol>(lhs: String, rhs: T) -> Bool {")
print(" return lhs == rhs.identifier")
print("}")
print("")
print("//MARK: - ReusableViewProtocol")
print("public protocol ReusableViewProtocol: IdentifiableProtocol {")
print(" var viewType: \(os.viewType).Type? { get }")
print("}")
print("")
print("public func ==<T: ReusableViewProtocol, U: ReusableViewProtocol>(lhs: T, rhs: U) -> Bool {")
print(" return lhs.identifier == rhs.identifier")
print("}")
print("")
print("//MARK: - Protocol Implementation")
print("extension \(os.storyboardSegueType): SegueProtocol {")
print("}")
print("")
if let reusableViews = os.resuableViews {
for reusableView in reusableViews {
print("extension \(reusableView): ReusableViewProtocol {")
print(" public var viewType: UIView.Type? { return self.dynamicType }")
print(" public var identifier: String? { return self.reuseIdentifier }")
print("}")
print("")
}
}
for controllerType in os.storyboardControllerTypes {
print("//MARK: - \(controllerType) extension")
print("extension \(controllerType) {")
print(" func performSegue<T: SegueProtocol>(segue: T, sender: AnyObject?) {")
print(" if let identifier = segue.identifier {")
print(" performSegueWithIdentifier(identifier, sender: sender)")
print(" }")
print(" }")
print("")
print(" func performSegue<T: SegueProtocol>(segue: T) {")
print(" performSegue(segue, sender: nil)")
print(" }")
print("}")
print("")
}
if os == OS.iOS {
print("//MARK: - UICollectionView")
print("")
print("extension UICollectionView {")
print("")
print(" func dequeueReusableCell<T: ReusableViewProtocol>(reusable: T, forIndexPath: NSIndexPath!) -> UICollectionViewCell? {")
print(" if let identifier = reusable.identifier {")
print(" return dequeueReusableCellWithReuseIdentifier(identifier, forIndexPath: forIndexPath)")
print(" }")
print(" return nil")
print(" }")
print("")
print(" func registerReusableCell<T: ReusableViewProtocol>(reusable: T) {")
print(" if let type = reusable.viewType, identifier = reusable.identifier {")
print(" registerClass(type, forCellWithReuseIdentifier: identifier)")
print(" }")
print(" }")
print("")
print(" func dequeueReusableSupplementaryViewOfKind<T: ReusableViewProtocol>(elementKind: String, withReusable reusable: T, forIndexPath: NSIndexPath!) -> UICollectionReusableView? {")
print(" if let identifier = reusable.identifier {")
print(" return dequeueReusableSupplementaryViewOfKind(elementKind, withReuseIdentifier: identifier, forIndexPath: forIndexPath)")
print(" }")
print(" return nil")
print(" }")
print("")
print(" func registerReusable<T: ReusableViewProtocol>(reusable: T, forSupplementaryViewOfKind elementKind: String) {")
print(" if let type = reusable.viewType, identifier = reusable.identifier {")
print(" registerClass(type, forSupplementaryViewOfKind: elementKind, withReuseIdentifier: identifier)")
print(" }")
print(" }")
print("}")
print("//MARK: - UITableView")
print("")
print("extension UITableView {")
print("")
print(" func dequeueReusableCell<T: ReusableViewProtocol>(reusable: T, forIndexPath: NSIndexPath!) -> UITableViewCell? {")
print(" if let identifier = reusable.identifier {")
print(" return dequeueReusableCellWithIdentifier(identifier, forIndexPath: forIndexPath)")
print(" }")
print(" return nil")
print(" }")
print("")
print(" func registerReusableCell<T: ReusableViewProtocol>(reusable: T) {")
print(" if let type = reusable.viewType, identifier = reusable.identifier {")
print(" registerClass(type, forCellReuseIdentifier: identifier)")
print(" }")
print(" }")
print("")
print(" func dequeueReusableHeaderFooter<T: ReusableViewProtocol>(reusable: T) -> UITableViewHeaderFooterView? {")
print(" if let identifier = reusable.identifier {")
print(" return dequeueReusableHeaderFooterViewWithIdentifier(identifier)")
print(" }")
print(" return nil")
print(" }")
print("")
print(" func registerReusableHeaderFooter<T: ReusableViewProtocol>(reusable: T) {")
print(" if let type = reusable.viewType, identifier = reusable.identifier {")
print(" registerClass(type, forHeaderFooterViewReuseIdentifier: identifier)")
print(" }")
print(" }")
print("}")
print("")
}
for file in storyboards {
file.storyboard.processViewControllers()
}
}
//MARK: MAIN()
if Process.arguments.count == 1 {
print("Invalid usage. Missing path to storyboard.")
exit(1)
}
let argument = Process.arguments[1]
var filePaths:[String] = []
let storyboardSuffix = ".storyboard"
if argument.hasSuffix(storyboardSuffix) {
filePaths = [argument]
} else if let s = findStoryboards(argument, suffix: storyboardSuffix) {
filePaths = s
}
let storyboardFiles = filePaths.map { StoryboardFile(filePath: $0) }
for os in OS.allValues {
let storyboardsForOS = storyboardFiles.filter({ $0.storyboard.os == os })
if !storyboardsForOS.isEmpty {
if storyboardsForOS.count != storyboardFiles.count {
print("#if os(\(os.rawValue))")
}
processStoryboards(storyboardsForOS, os: os)
if storyboardsForOS.count != storyboardFiles.count {
print("#endif")
}
}
}
exit(0)
| mit | 6b3a8ab92d4c9aa5992c08c9265fd60c | 34.316568 | 195 | 0.537363 | 5.407475 | false | false | false | false |
aschwaighofer/swift | test/AutoDiff/Sema/derivative_attr_type_checking.swift | 1 | 36340 | // RUN: %target-swift-frontend-typecheck -verify %s
import _Differentiation
// Dummy `Differentiable`-conforming type.
struct DummyTangentVector: Differentiable & AdditiveArithmetic {
static var zero: Self { Self() }
static func + (_: Self, _: Self) -> Self { Self() }
static func - (_: Self, _: Self) -> Self { Self() }
typealias TangentVector = Self
}
// Test top-level functions.
func id(_ x: Float) -> Float {
return x
}
@derivative(of: id)
func jvpId(x: Float) -> (value: Float, differential: (Float) -> (Float)) {
return (x, { $0 })
}
@derivative(of: id, wrt: x)
func vjpIdExplicitWrt(x: Float) -> (value: Float, pullback: (Float) -> Float) {
return (x, { $0 })
}
func generic<T: Differentiable>(_ x: T, _ y: T) -> T {
return x
}
@derivative(of: generic)
func jvpGeneric<T: Differentiable>(x: T, y: T) -> (
value: T, differential: (T.TangentVector, T.TangentVector) -> T.TangentVector
) {
return (x, { $0 + $1 })
}
@derivative(of: generic)
func vjpGenericExtraGenericRequirements<T: Differentiable & FloatingPoint>(
x: T, y: T
) -> (value: T, pullback: (T) -> (T, T)) where T == T.TangentVector {
return (x, { ($0, $0) })
}
// Test `wrt` parameter clauses.
func add(x: Float, y: Float) -> Float {
return x + y
}
@derivative(of: add, wrt: x) // ok
func vjpAddWrtX(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float)) {
return (x + y, { $0 })
}
@derivative(of: add, wrt: (x, y)) // ok
func vjpAddWrtXY(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x + y, { ($0, $0) })
}
// Test index-based `wrt` parameters.
func subtract(x: Float, y: Float) -> Float {
return x - y
}
@derivative(of: subtract, wrt: (0, y)) // ok
func vjpSubtractWrt0Y(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x - y, { ($0, $0) })
}
@derivative(of: subtract, wrt: (1)) // ok
func vjpSubtractWrt1(x: Float, y: Float) -> (value: Float, pullback: (Float) -> Float) {
return (x - y, { $0 })
}
// Test invalid original function.
// expected-error @+1 {{cannot find 'nonexistentFunction' in scope}}
@derivative(of: nonexistentFunction)
func vjpOriginalFunctionNotFound(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
// Test `@derivative` attribute where `value:` result does not conform to `Differentiable`.
// Invalid original function should be diagnosed first.
// expected-error @+1 {{cannot find 'nonexistentFunction' in scope}}
@derivative(of: nonexistentFunction)
func vjpOriginalFunctionNotFound2(_ x: Float) -> (value: Int, pullback: (Float) -> Float) {
fatalError()
}
// Test incorrect `@derivative` declaration type.
// expected-note @+1 {{'incorrectDerivativeType' defined here}}
func incorrectDerivativeType(_ x: Float) -> Float {
return x
}
// expected-error @+1 {{'@derivative(of:)' attribute requires function to return a two-element tuple; first element must have label 'value:' and second element must have label 'pullback:' or 'differential:'}}
@derivative(of: incorrectDerivativeType)
func jvpResultIncorrect(x: Float) -> Float {
return x
}
// expected-error @+1 {{'@derivative(of:)' attribute requires function to return a two-element tuple; first element must have label 'value:'}}
@derivative(of: incorrectDerivativeType)
func vjpResultIncorrectFirstLabel(x: Float) -> (Float, (Float) -> Float) {
return (x, { $0 })
}
// expected-error @+1 {{'@derivative(of:)' attribute requires function to return a two-element tuple; second element must have label 'pullback:' or 'differential:'}}
@derivative(of: incorrectDerivativeType)
func vjpResultIncorrectSecondLabel(x: Float) -> (value: Float, (Float) -> Float) {
return (x, { $0 })
}
// expected-error @+1 {{could not find function 'incorrectDerivativeType' with expected type '(Int) -> Int'}}
@derivative(of: incorrectDerivativeType)
func vjpResultNotDifferentiable(x: Int) -> (
value: Int, pullback: (Int) -> Int
) {
return (x, { $0 })
}
// expected-error @+2 {{function result's 'pullback' type does not match 'incorrectDerivativeType'}}
// expected-note @+3 {{'pullback' does not have expected type '(Float.TangentVector) -> Float.TangentVector' (aka '(Float) -> Float')}}
@derivative(of: incorrectDerivativeType)
func vjpResultIncorrectPullbackType(x: Float) -> (
value: Float, pullback: (Double) -> Double
) {
return (x, { $0 })
}
// Test invalid `wrt:` differentiation parameters.
func invalidWrtParam(_ x: Float, _ y: Float) -> Float {
return x
}
// expected-error @+1 {{unknown parameter name 'z'}}
@derivative(of: add, wrt: z)
func vjpUnknownParam(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float)) {
return (x + y, { $0 })
}
// expected-error @+1 {{parameters must be specified in original order}}
@derivative(of: invalidWrtParam, wrt: (y, x))
func vjpParamOrderNotIncreasing(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x + y, { ($0, $0) })
}
// expected-error @+1 {{'self' parameter is only applicable to instance methods}}
@derivative(of: invalidWrtParam, wrt: self)
func vjpInvalidSelfParam(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x + y, { ($0, $0) })
}
// expected-error @+1 {{parameter index is larger than total number of parameters}}
@derivative(of: invalidWrtParam, wrt: 2)
func vjpSubtractWrt2(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x - y, { ($0, $0) })
}
// expected-error @+1 {{parameters must be specified in original order}}
@derivative(of: invalidWrtParam, wrt: (1, x))
func vjpSubtractWrt1x(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x - y, { ($0, $0) })
}
// expected-error @+1 {{parameters must be specified in original order}}
@derivative(of: invalidWrtParam, wrt: (1, 0))
func vjpSubtractWrt10(x: Float, y: Float) -> (value: Float, pullback: (Float) -> (Float, Float)) {
return (x - y, { ($0, $0) })
}
func noParameters() -> Float {
return 1
}
// expected-error @+1 {{'vjpNoParameters()' has no parameters to differentiate with respect to}}
@derivative(of: noParameters)
func vjpNoParameters() -> (value: Float, pullback: (Float) -> Float) {
return (1, { $0 })
}
func noDifferentiableParameters(x: Int) -> Float {
return 1
}
// expected-error @+1 {{no differentiation parameters could be inferred; must differentiate with respect to at least one parameter conforming to 'Differentiable'}}
@derivative(of: noDifferentiableParameters)
func vjpNoDifferentiableParameters(x: Int) -> (
value: Float, pullback: (Float) -> Int
) {
return (1, { _ in 0 })
}
func functionParameter(_ fn: (Float) -> Float) -> Float {
return fn(1)
}
// expected-error @+1 {{can only differentiate with respect to parameters that conform to 'Differentiable', but '(Float) -> Float' does not conform to 'Differentiable'}}
@derivative(of: functionParameter, wrt: fn)
func vjpFunctionParameter(_ fn: (Float) -> Float) -> (
value: Float, pullback: (Float) -> Float
) {
return (functionParameter(fn), { $0 })
}
// Test static methods.
protocol StaticMethod: Differentiable {
static func foo(_ x: Float) -> Float
static func generic<T: Differentiable>(_ x: T) -> T
}
extension StaticMethod {
static func foo(_ x: Float) -> Float { x }
static func generic<T: Differentiable>(_ x: T) -> T { x }
}
extension StaticMethod {
@derivative(of: foo)
static func jvpFoo(x: Float) -> (value: Float, differential: (Float) -> Float)
{
return (x, { $0 })
}
// Test qualified declaration name.
@derivative(of: StaticMethod.foo)
static func vjpFoo(x: Float) -> (value: Float, pullback: (Float) -> Float) {
return (x, { $0 })
}
@derivative(of: generic)
static func vjpGeneric<T: Differentiable>(_ x: T) -> (
value: T, pullback: (T.TangentVector) -> (T.TangentVector)
) {
return (x, { $0 })
}
// expected-error @+1 {{'self' parameter is only applicable to instance methods}}
@derivative(of: foo, wrt: (self, x))
static func vjpFooWrtSelf(x: Float) -> (value: Float, pullback: (Float) -> Float) {
return (x, { $0 })
}
}
// Test instance methods.
protocol InstanceMethod: Differentiable {
func foo(_ x: Self) -> Self
func generic<T: Differentiable>(_ x: T) -> Self
}
extension InstanceMethod {
// expected-note @+1 {{'foo' defined here}}
func foo(_ x: Self) -> Self { x }
// expected-note @+1 {{'generic' defined here}}
func generic<T: Differentiable>(_ x: T) -> Self { self }
}
extension InstanceMethod {
@derivative(of: foo)
func jvpFoo(x: Self) -> (
value: Self, differential: (TangentVector, TangentVector) -> (TangentVector)
) {
return (x, { $0 + $1 })
}
// Test qualified declaration name.
@derivative(of: InstanceMethod.foo, wrt: x)
func jvpFooWrtX(x: Self) -> (
value: Self, differential: (TangentVector) -> (TangentVector)
) {
return (x, { $0 })
}
@derivative(of: generic)
func vjpGeneric<T: Differentiable>(_ x: T) -> (
value: Self, pullback: (TangentVector) -> (TangentVector, T.TangentVector)
) {
return (self, { ($0, .zero) })
}
@derivative(of: generic, wrt: (self, x))
func jvpGenericWrt<T: Differentiable>(_ x: T) -> (value: Self, differential: (TangentVector, T.TangentVector) -> TangentVector) {
return (self, { dself, dx in dself })
}
// expected-error @+1 {{'self' parameter must come first in the parameter list}}
@derivative(of: generic, wrt: (x, self))
func jvpGenericWrtSelf<T: Differentiable>(_ x: T) -> (value: Self, differential: (TangentVector, T.TangentVector) -> TangentVector) {
return (self, { dself, dx in dself })
}
}
extension InstanceMethod {
// If `Self` conforms to `Differentiable`, then `Self` is inferred to be a differentiation parameter.
// expected-error @+2 {{function result's 'pullback' type does not match 'foo'}}
// expected-note @+3 {{'pullback' does not have expected type '(Self.TangentVector) -> (Self.TangentVector, Self.TangentVector)'}}
@derivative(of: foo)
func vjpFoo(x: Self) -> (
value: Self, pullback: (TangentVector) -> TangentVector
) {
return (x, { $0 })
}
// If `Self` conforms to `Differentiable`, then `Self` is inferred to be a differentiation parameter.
// expected-error @+2 {{function result's 'pullback' type does not match 'generic'}}
// expected-note @+3 {{'pullback' does not have expected type '(Self.TangentVector) -> (Self.TangentVector, T.TangentVector)'}}
@derivative(of: generic)
func vjpGeneric<T: Differentiable>(_ x: T) -> (
value: Self, pullback: (TangentVector) -> T.TangentVector
) {
return (self, { _ in .zero })
}
}
// Test `@derivative` declaration with more constrained generic signature.
func req1<T>(_ x: T) -> T {
return x
}
@derivative(of: req1)
func vjpExtraConformanceConstraint<T: Differentiable>(_ x: T) -> (
value: T, pullback: (T.TangentVector) -> T.TangentVector
) {
return (x, { $0 })
}
func req2<T, U>(_ x: T, _ y: U) -> T {
return x
}
@derivative(of: req2)
func vjpExtraConformanceConstraints<T: Differentiable, U: Differentiable>( _ x: T, _ y: U) -> (
value: T, pullback: (T) -> (T, U)
) where T == T.TangentVector, U == U.TangentVector, T: CustomStringConvertible {
return (x, { ($0, .zero) })
}
// Test `@derivative` declaration with extra same-type requirements.
func req3<T>(_ x: T) -> T {
return x
}
@derivative(of: req3)
func vjpSameTypeRequirementsGenericParametersAllConcrete<T>(_ x: T) -> (
value: T, pullback: (T.TangentVector) -> T.TangentVector
) where T: Differentiable, T.TangentVector == Float {
return (x, { $0 })
}
struct Wrapper<T: Equatable>: Equatable {
var x: T
init(_ x: T) { self.x = x }
}
extension Wrapper: AdditiveArithmetic where T: AdditiveArithmetic {
static var zero: Self { .init(.zero) }
static func + (lhs: Self, rhs: Self) -> Self { .init(lhs.x + rhs.x) }
static func - (lhs: Self, rhs: Self) -> Self { .init(lhs.x - rhs.x) }
}
extension Wrapper: Differentiable where T: Differentiable, T == T.TangentVector {
typealias TangentVector = Wrapper<T.TangentVector>
}
extension Wrapper where T: Differentiable, T == T.TangentVector {
@derivative(of: init(_:))
static func vjpInit(_ x: T) -> (value: Self, pullback: (Wrapper<T>.TangentVector) -> (T)) {
fatalError()
}
}
// Test class methods.
class Super {
@differentiable
func foo(_ x: Float) -> Float {
return x
}
@derivative(of: foo)
func vjpFoo(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
return (foo(x), { v in v })
}
}
class Sub: Super {
// TODO(TF-649): Enable `@derivative` to override derivatives for original
// declaration defined in superclass.
// expected-error @+1 {{'foo' is not defined in the current type context}}
@derivative(of: foo)
override func vjpFoo(_ x: Float) -> (value: Float, pullback: (Float) -> Float)
{
return (foo(x), { v in v })
}
}
// Test non-`func` original declarations.
struct Struct<T> {
var x: T
}
extension Struct: Equatable where T: Equatable {}
extension Struct: Differentiable & AdditiveArithmetic
where T: Differentiable & AdditiveArithmetic {
static var zero: Self {
fatalError()
}
static func + (lhs: Self, rhs: Self) -> Self {
fatalError()
}
static func - (lhs: Self, rhs: Self) -> Self {
fatalError()
}
typealias TangentVector = Struct<T.TangentVector>
mutating func move(along direction: TangentVector) {
x.move(along: direction.x)
}
}
// Test computed properties.
extension Struct {
var computedProperty: T { x }
}
extension Struct where T: Differentiable & AdditiveArithmetic {
@derivative(of: computedProperty)
func vjpProperty() -> (value: T, pullback: (T.TangentVector) -> TangentVector) {
return (x, { v in .init(x: v) })
}
}
// Test initializers.
extension Struct {
init(_ x: Float) {}
init(_ x: T, y: Float) {}
}
extension Struct where T: Differentiable & AdditiveArithmetic {
@derivative(of: init)
static func vjpInit(_ x: Float) -> (
value: Struct, pullback: (TangentVector) -> Float
) {
return (.init(x), { _ in .zero })
}
@derivative(of: init(_:y:))
static func vjpInit2(_ x: T, _ y: Float) -> (
value: Struct, pullback: (TangentVector) -> (T.TangentVector, Float)
) {
return (.init(x, y: y), { _ in (.zero, .zero) })
}
}
// Test subscripts.
extension Struct {
subscript() -> Float {
get { 1 }
set {}
}
subscript(float float: Float) -> Float { 1 }
subscript<T: Differentiable>(x: T) -> T { x }
}
extension Struct where T: Differentiable & AdditiveArithmetic {
@derivative(of: subscript)
func vjpSubscript() -> (value: Float, pullback: (Float) -> TangentVector) {
return (1, { _ in .zero })
}
@derivative(of: subscript(float:), wrt: self)
func vjpSubscriptLabelled(float: Float) -> (value: Float, pullback: (Float) -> TangentVector) {
return (1, { _ in .zero })
}
@derivative(of: subscript(_:), wrt: self)
func vjpSubscriptGeneric<T: Differentiable>(x: T) -> (value: T, pullback: (T.TangentVector) -> TangentVector) {
return (x, { _ in .zero })
}
}
// Test duplicate `@derivative` attribute.
func duplicate(_ x: Float) -> Float { x }
// expected-note @+1 {{other attribute declared here}}
@derivative(of: duplicate)
func jvpDuplicate1(_ x: Float) -> (value: Float, differential: (Float) -> Float) {
return (duplicate(x), { $0 })
}
// expected-error @+1 {{a derivative already exists for 'duplicate'}}
@derivative(of: duplicate)
func jvpDuplicate2(_ x: Float) -> (value: Float, differential: (Float) -> Float) {
return (duplicate(x), { $0 })
}
// Test invalid original declaration kind.
var globalVariable: Float
// expected-error @+1 {{'globalVariable' is not a 'func', 'init', 'subscript', or 'var' computed property declaration}}
@derivative(of: globalVariable)
func invalidOriginalDeclaration(x: Float) -> (
value: Float, differential: (Float) -> (Float)
) {
return (x, { $0 })
}
// Test ambiguous original declaration.
protocol P1 {}
protocol P2 {}
func ambiguous<T: P1>(_ x: T) -> T { x }
func ambiguous<T: P2>(_ x: T) -> T { x }
// expected-error @+1 {{ambiguous reference to 'ambiguous' in '@derivative' attribute}}
@derivative(of: ambiguous)
func jvpAmbiguous<T: P1 & P2 & Differentiable>(x: T)
-> (value: T, differential: (T.TangentVector) -> (T.TangentVector))
{
return (x, { $0 })
}
// Test no valid original declaration.
// Original declarations are invalid because they have extra generic
// requirements unsatisfied by the `@derivative` function.
func invalid<T: BinaryFloatingPoint>(x: T) -> T { x }
func invalid<T: CustomStringConvertible>(x: T) -> T { x }
func invalid<T: FloatingPoint>(x: T) -> T { x }
// expected-error @+1 {{could not find function 'invalid' with expected type '<T where T : Differentiable> (x: T) -> T'}}
@derivative(of: invalid)
func jvpInvalid<T: Differentiable>(x: T) -> (
value: T, differential: (T.TangentVector) -> T.TangentVector
) {
return (x, { $0 })
}
// Test invalid derivative type context: instance vs static method mismatch.
struct InvalidTypeContext<T: Differentiable> {
static func staticMethod(_ x: T) -> T { x }
// expected-error @+1 {{could not find function 'staticMethod' with expected type '<T where T : Differentiable> (InvalidTypeContext<T>) -> (T) -> T'}}
@derivative(of: staticMethod)
func jvpStatic(_ x: T) -> (
value: T, differential: (T.TangentVector) -> (T.TangentVector)
) {
return (x, { $0 })
}
}
// Test stored property original declaration.
struct HasStoredProperty {
// expected-note @+1 {{'stored' declared here}}
var stored: Float
}
extension HasStoredProperty: Differentiable & AdditiveArithmetic {
static var zero: Self {
fatalError()
}
static func + (lhs: Self, rhs: Self) -> Self {
fatalError()
}
static func - (lhs: Self, rhs: Self) -> Self {
fatalError()
}
typealias TangentVector = Self
}
extension HasStoredProperty {
// expected-error @+1 {{cannot register derivative for stored property 'stored'}}
@derivative(of: stored)
func vjpStored() -> (value: Float, pullback: (Float) -> TangentVector) {
return (stored, { _ in .zero })
}
}
// Test derivative registration for protocol requirements. Currently unsupported.
// TODO(TF-982): Lift this restriction and add proper support.
protocol ProtocolRequirementDerivative {
func requirement(_ x: Float) -> Float
}
extension ProtocolRequirementDerivative {
// NOTE: the error is misleading because `findAbstractFunctionDecl` in
// TypeCheckAttr.cpp is not setup to show customized error messages for
// invalid original function candidates.
// expected-error @+1 {{could not find function 'requirement' with expected type '<Self where Self : ProtocolRequirementDerivative> (Self) -> (Float) -> Float'}}
@derivative(of: requirement)
func vjpRequirement(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
}
// Test `inout` parameters.
func multipleSemanticResults(_ x: inout Float) -> Float {
return x
}
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@derivative(of: multipleSemanticResults)
func vjpMultipleSemanticResults(x: inout Float) -> (
value: Float, pullback: (Float) -> Float
) {
return (multipleSemanticResults(&x), { $0 })
}
struct InoutParameters: Differentiable {
typealias TangentVector = DummyTangentVector
mutating func move(along _: TangentVector) {}
}
extension InoutParameters {
// expected-note @+1 4 {{'staticMethod(_:rhs:)' defined here}}
static func staticMethod(_ lhs: inout Self, rhs: Self) {}
// Test wrt `inout` parameter.
@derivative(of: staticMethod)
static func vjpWrtInout(_ lhs: inout Self, _ rhs: Self) -> (
value: Void, pullback: (inout TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'pullback' type does not match 'staticMethod(_:rhs:)'}}
@derivative(of: staticMethod)
static func vjpWrtInoutMismatch(_ lhs: inout Self, _ rhs: Self) -> (
// expected-note @+1 {{'pullback' does not have expected type '(inout InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(inout DummyTangentVector) -> DummyTangentVector')}}
value: Void, pullback: (TangentVector) -> TangentVector
) { fatalError() }
@derivative(of: staticMethod)
static func jvpWrtInout(_ lhs: inout Self, _ rhs: Self) -> (
value: Void, differential: (inout TangentVector, TangentVector) -> Void
) { fatalError() }
// expected-error @+1 {{function result's 'differential' type does not match 'staticMethod(_:rhs:)'}}
@derivative(of: staticMethod)
static func jvpWrtInoutMismatch(_ lhs: inout Self, _ rhs: Self) -> (
// expected-note @+1 {{'differential' does not have expected type '(inout InoutParameters.TangentVector, InoutParameters.TangentVector) -> ()' (aka '(inout DummyTangentVector, DummyTangentVector) -> ()')}}
value: Void, differential: (TangentVector, TangentVector) -> Void
) { fatalError() }
// Test non-wrt `inout` parameter.
@derivative(of: staticMethod, wrt: rhs)
static func vjpNotWrtInout(_ lhs: inout Self, _ rhs: Self) -> (
value: Void, pullback: (TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'pullback' type does not match 'staticMethod(_:rhs:)'}}
@derivative(of: staticMethod, wrt: rhs)
static func vjpNotWrtInoutMismatch(_ lhs: inout Self, _ rhs: Self) -> (
// expected-note @+1 {{'pullback' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}}
value: Void, pullback: (inout TangentVector) -> TangentVector
) { fatalError() }
@derivative(of: staticMethod, wrt: rhs)
static func jvpNotWrtInout(_ lhs: inout Self, _ rhs: Self) -> (
value: Void, differential: (TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'differential' type does not match 'staticMethod(_:rhs:)'}}
@derivative(of: staticMethod, wrt: rhs)
static func jvpNotWrtInout(_ lhs: inout Self, _ rhs: Self) -> (
// expected-note @+1 {{'differential' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}}
value: Void, differential: (inout TangentVector) -> TangentVector
) { fatalError() }
}
extension InoutParameters {
// expected-note @+1 4 {{'mutatingMethod' defined here}}
mutating func mutatingMethod(_ other: Self) {}
// Test wrt `inout` `self` parameter.
@derivative(of: mutatingMethod)
mutating func vjpWrtInout(_ other: Self) -> (
value: Void, pullback: (inout TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'pullback' type does not match 'mutatingMethod'}}
@derivative(of: mutatingMethod)
mutating func vjpWrtInoutMismatch(_ other: Self) -> (
// expected-note @+1 {{'pullback' does not have expected type '(inout InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(inout DummyTangentVector) -> DummyTangentVector')}}
value: Void, pullback: (TangentVector) -> TangentVector
) { fatalError() }
@derivative(of: mutatingMethod)
mutating func jvpWrtInout(_ other: Self) -> (
value: Void, differential: (inout TangentVector, TangentVector) -> Void
) { fatalError() }
// expected-error @+1 {{function result's 'differential' type does not match 'mutatingMethod'}}
@derivative(of: mutatingMethod)
mutating func jvpWrtInoutMismatch(_ other: Self) -> (
// expected-note @+1 {{'differential' does not have expected type '(inout InoutParameters.TangentVector, InoutParameters.TangentVector) -> ()' (aka '(inout DummyTangentVector, DummyTangentVector) -> ()')}}
value: Void, differential: (TangentVector, TangentVector) -> Void
) { fatalError() }
// Test non-wrt `inout` `self` parameter.
@derivative(of: mutatingMethod, wrt: other)
mutating func vjpNotWrtInout(_ other: Self) -> (
value: Void, pullback: (TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'pullback' type does not match 'mutatingMethod'}}
@derivative(of: mutatingMethod, wrt: other)
mutating func vjpNotWrtInoutMismatch(_ other: Self) -> (
// expected-note @+1 {{'pullback' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}}
value: Void, pullback: (inout TangentVector) -> TangentVector
) { fatalError() }
@derivative(of: mutatingMethod, wrt: other)
mutating func jvpNotWrtInout(_ other: Self) -> (
value: Void, differential: (TangentVector) -> TangentVector
) { fatalError() }
// expected-error @+1 {{function result's 'differential' type does not match 'mutatingMethod'}}
@derivative(of: mutatingMethod, wrt: other)
mutating func jvpNotWrtInoutMismatch(_ other: Self) -> (
// expected-note @+1 {{'differential' does not have expected type '(InoutParameters.TangentVector) -> InoutParameters.TangentVector' (aka '(DummyTangentVector) -> DummyTangentVector')}}
value: Void, differential: (TangentVector, TangentVector) -> Void
) { fatalError() }
}
// Test multiple semantic results.
extension InoutParameters {
func multipleSemanticResults(_ x: inout Float) -> Float { x }
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@derivative(of: multipleSemanticResults)
func vjpMultipleSemanticResults(_ x: inout Float) -> (
value: Float, pullback: (inout Float) -> Void
) { fatalError() }
func inoutVoid(_ x: Float, _ void: inout Void) -> Float {}
// expected-error @+1 {{cannot differentiate functions with both an 'inout' parameter and a result}}
@derivative(of: inoutVoid)
func vjpInoutVoidParameter(_ x: Float, _ void: inout Void) -> (
value: Float, pullback: (inout Float) -> Void
) { fatalError() }
}
// Test original/derivative function `inout` parameter mismatches.
extension InoutParameters {
func inoutParameterMismatch(_ x: Float) {}
// expected-error @+1 {{could not find function 'inoutParameterMismatch' with expected type '(InoutParameters) -> (inout Float) -> Void'}}
@derivative(of: inoutParameterMismatch)
func vjpInoutParameterMismatch(_ x: inout Float) -> (value: Void, pullback: (inout Float) -> Void) {
fatalError()
}
func mutatingMismatch(_ x: Float) {}
// expected-error @+1 {{could not find function 'mutatingMismatch' with expected type '(inout InoutParameters) -> (Float) -> Void'}}
@derivative(of: mutatingMismatch)
mutating func vjpMutatingMismatch(_ x: Float) -> (value: Void, pullback: (inout Float) -> Void) {
fatalError()
}
}
// Test cross-file derivative registration.
extension FloatingPoint where Self: Differentiable {
@usableFromInline
@derivative(of: rounded)
func vjpRounded() -> (
value: Self,
pullback: (Self.TangentVector) -> (Self.TangentVector)
) {
fatalError()
}
}
extension Differentiable where Self: AdditiveArithmetic {
// expected-error @+1 {{'+' is not defined in the current type context}}
@derivative(of: +)
static func vjpPlus(x: Self, y: Self) -> (
value: Self,
pullback: (Self.TangentVector) -> (Self.TangentVector, Self.TangentVector)
) {
return (x + y, { v in (v, v) })
}
}
extension AdditiveArithmetic
where Self: Differentiable, Self == Self.TangentVector {
// expected-error @+1 {{could not find function '+' with expected type '<Self where Self : Differentiable, Self == Self.TangentVector> (Self) -> (Self, Self) -> Self'}}
@derivative(of: +)
func vjpPlusInstanceMethod(x: Self, y: Self) -> (
value: Self, pullback: (Self) -> (Self, Self)
) {
return (x + y, { v in (v, v) })
}
}
// Test derivatives of default implementations.
protocol HasADefaultImplementation {
func req(_ x: Float) -> Float
}
extension HasADefaultImplementation {
func req(_ x: Float) -> Float { x }
// ok
@derivative(of: req)
func req(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
(x, { 10 * $0 })
}
}
// Test default derivatives of requirements.
protocol HasADefaultDerivative {
func req(_ x: Float) -> Float
}
extension HasADefaultDerivative {
// TODO(TF-982): Make this ok.
// expected-error @+1 {{could not find function 'req'}}
@derivative(of: req)
func req(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
(x, { 10 * $0 })
}
}
// MARK: - Original function visibility = derivative function visibility
public func public_original_public_derivative(_ x: Float) -> Float { x }
@derivative(of: public_original_public_derivative)
public func _public_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
public func public_original_usablefrominline_derivative(_ x: Float) -> Float { x }
@usableFromInline
@derivative(of: public_original_usablefrominline_derivative)
func _public_original_usablefrominline_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
func internal_original_internal_derivative(_ x: Float) -> Float { x }
@derivative(of: internal_original_internal_derivative)
func _internal_original_internal_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
private func private_original_private_derivative(_ x: Float) -> Float { x }
@derivative(of: private_original_private_derivative)
private func _private_original_private_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
fileprivate func fileprivate_original_fileprivate_derivative(_ x: Float) -> Float { x }
@derivative(of: fileprivate_original_fileprivate_derivative)
fileprivate func _fileprivate_original_fileprivate_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
// MARK: - Original function visibility < derivative function visibility
@usableFromInline
func usablefrominline_original_public_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_usablefrominline_original_public_derivative' is public, but original function 'usablefrominline_original_public_derivative' is internal}}
@derivative(of: usablefrominline_original_public_derivative)
// expected-note @+1 {{mark the derivative function as 'internal' to match the original function}} {{1-7=internal}}
public func _usablefrominline_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
func internal_original_public_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_internal_original_public_derivative' is public, but original function 'internal_original_public_derivative' is internal}}
@derivative(of: internal_original_public_derivative)
// expected-note @+1 {{mark the derivative function as 'internal' to match the original function}} {{1-7=internal}}
public func _internal_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
private func private_original_usablefrominline_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_usablefrominline_derivative' is internal, but original function 'private_original_usablefrominline_derivative' is private}}
@derivative(of: private_original_usablefrominline_derivative)
@usableFromInline
// expected-note @+1 {{mark the derivative function as 'private' to match the original function}} {{1-1=private }}
func _private_original_usablefrominline_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
private func private_original_public_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_public_derivative' is public, but original function 'private_original_public_derivative' is private}}
@derivative(of: private_original_public_derivative)
// expected-note @+1 {{mark the derivative function as 'private' to match the original function}} {{1-7=private}}
public func _private_original_public_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
private func private_original_internal_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_internal_derivative' is internal, but original function 'private_original_internal_derivative' is private}}
@derivative(of: private_original_internal_derivative)
// expected-note @+1 {{mark the derivative function as 'private' to match the original function}}
func _private_original_internal_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
fileprivate func fileprivate_original_private_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_fileprivate_original_private_derivative' is private, but original function 'fileprivate_original_private_derivative' is fileprivate}}
@derivative(of: fileprivate_original_private_derivative)
// expected-note @+1 {{mark the derivative function as 'fileprivate' to match the original function}} {{1-8=fileprivate}}
private func _fileprivate_original_private_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
private func private_original_fileprivate_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_private_original_fileprivate_derivative' is fileprivate, but original function 'private_original_fileprivate_derivative' is private}}
@derivative(of: private_original_fileprivate_derivative)
// expected-note @+1 {{mark the derivative function as 'private' to match the original function}} {{1-12=private}}
fileprivate func _private_original_fileprivate_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
// MARK: - Original function visibility > derivative function visibility
public func public_original_private_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_public_original_private_derivative' is fileprivate, but original function 'public_original_private_derivative' is public}}
@derivative(of: public_original_private_derivative)
// expected-note @+1 {{mark the derivative function as '@usableFromInline' to match the original function}} {{1-1=@usableFromInline }}
fileprivate func _public_original_private_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
public func public_original_internal_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_public_original_internal_derivative' is internal, but original function 'public_original_internal_derivative' is public}}
@derivative(of: public_original_internal_derivative)
// expected-note @+1 {{mark the derivative function as '@usableFromInline' to match the original function}} {{1-1=@usableFromInline }}
func _public_original_internal_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
func internal_original_fileprivate_derivative(_ x: Float) -> Float { x }
// expected-error @+1 {{derivative function must have same access level as original function; derivative function '_internal_original_fileprivate_derivative' is fileprivate, but original function 'internal_original_fileprivate_derivative' is internal}}
@derivative(of: internal_original_fileprivate_derivative)
// expected-note @+1 {{mark the derivative function as 'internal' to match the original function}} {{1-12=internal}}
fileprivate func _internal_original_fileprivate_derivative(_ x: Float) -> (value: Float, pullback: (Float) -> Float) {
fatalError()
}
| apache-2.0 | 67a0411f1bf410cf201f6718a13f93b9 | 38.329004 | 256 | 0.690259 | 3.824861 | false | false | false | false |
neekeetab/VKAudioPlayer | VKAudioPlayer/TableViewController+AudioCellDelegate.swift | 1 | 1232 | //
// TableViewController+AudioCellDelegate.swift
// VKAudioPlayer
//
// Created by Nikita Belousov on 6/21/16.
// Copyright © 2016 Nikita Belousov. All rights reserved.
//
import UIKit
import VK_ios_sdk
extension TableViewController: AudioCellDelegate {
func addButtonPressed(sender: AudioCell) {
let indexPath = tableView.indexPathForCell(sender)
let audioItem = audioItemForIndexPath(indexPath!)
let request = VKRequest.addAudioRequest(audioItem)
request.executeWithResultBlock({ response in
self.showMessage("", title: "Audio has been added")
sender.ownedByUser = true
}, errorBlock: { error in
self.showError(error.description)
sender.ownedByUser = false
})
}
func downloadButtonPressed(sender: AudioCell) {
CacheController.sharedCacheController.downloadAudioItem(sender.audioItem!)
}
func cancelButtonPressed(sender: AudioCell) {
CacheController.sharedCacheController.cancelDownloadingAudioItem(sender.audioItem!)
}
func uncacheButtonPressed(sender: AudioCell) {
CacheController.sharedCacheController.uncacheAudioItem(sender.audioItem!)
}
}
| mit | 956f270aed28595e0717928116b1dcec | 29.775 | 91 | 0.694557 | 4.62782 | false | false | false | false |
naokits/my-programming-marathon | iPhoneSensorDemo/Pods/RxSwift/RxSwift/Subjects/PublishSubject.swift | 16 | 3499 | //
// PublishSubject.swift
// Rx
//
// Created by Krunoslav Zaher on 2/11/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
/**
Represents an object that is both an observable sequence as well as an observer.
Each notification is broadcasted to all subscribed observers.
*/
final public class PublishSubject<Element>
: Observable<Element>
, SubjectType
, Cancelable
, ObserverType
, SynchronizedUnsubscribeType {
public typealias SubjectObserverType = PublishSubject<Element>
typealias DisposeKey = Bag<AnyObserver<Element>>.KeyType
private var _lock = NSRecursiveLock()
// state
private var _disposed = false
private var _observers = Bag<AnyObserver<Element>>()
private var _stopped = false
private var _stoppedEvent = nil as Event<Element>?
/**
Indicates whether the subject has been disposed.
*/
public var disposed: Bool {
return _disposed
}
/**
Creates a subject.
*/
public override init() {
super.init()
}
/**
Notifies all subscribed observers about next event.
- parameter event: Event to send to the observers.
*/
public func on(event: Event<Element>) {
_lock.lock(); defer { _lock.unlock() }
_synchronized_on(event)
}
func _synchronized_on(event: Event<E>) {
switch event {
case .Next(_):
if _disposed || _stopped {
return
}
_observers.on(event)
case .Completed, .Error:
if _stoppedEvent == nil {
_stoppedEvent = event
_stopped = true
_observers.on(event)
_observers.removeAll()
}
}
}
/**
Subscribes an observer to the subject.
- parameter observer: Observer to subscribe to the subject.
- returns: Disposable object that can be used to unsubscribe the observer from the subject.
*/
public override func subscribe<O : ObserverType where O.E == Element>(observer: O) -> Disposable {
_lock.lock(); defer { _lock.unlock() }
return _synchronized_subscribe(observer)
}
func _synchronized_subscribe<O : ObserverType where O.E == E>(observer: O) -> Disposable {
if let stoppedEvent = _stoppedEvent {
observer.on(stoppedEvent)
return NopDisposable.instance
}
if _disposed {
observer.on(.Error(RxError.Disposed(object: self)))
return NopDisposable.instance
}
let key = _observers.insert(observer.asObserver())
return SubscriptionDisposable(owner: self, key: key)
}
func synchronizedUnsubscribe(disposeKey: DisposeKey) {
_lock.lock(); defer { _lock.unlock() }
_synchronized_unsubscribe(disposeKey)
}
func _synchronized_unsubscribe(disposeKey: DisposeKey) {
_ = _observers.removeKey(disposeKey)
}
/**
Returns observer interface for subject.
*/
public func asObserver() -> PublishSubject<Element> {
return self
}
/**
Unsubscribe all observers and release resources.
*/
public func dispose() {
_lock.lock(); defer { _lock.unlock() }
_synchronized_dispose()
}
final func _synchronized_dispose() {
_disposed = true
_observers.removeAll()
_stoppedEvent = nil
}
} | mit | ab1fa8df81b021bf509b0276a45f1673 | 25.709924 | 102 | 0.595769 | 4.878661 | false | false | false | false |
ifabijanovic/swtor-holonet | ios/HoloNet/Module/Settings/UI/SettingPickerDelegate.swift | 1 | 2365 | //
// SettingPickerDelegate
// SWTOR HoloNet
//
// Created by Ivan Fabijanovic on 04/08/15.
// Copyright (c) 2015 Ivan Fabijanović. All rights reserved.
//
import UIKit
struct SettingPickerOption<T: Equatable> {
let index: Int
let value: T
}
class SettingPickerDelegate<T: Equatable> {
fileprivate let options: [SettingPickerOption<T>]
fileprivate var selectedIndexPath: IndexPath
init(options: [SettingPickerOption<T>]) {
self.options = options
self.selectedIndexPath = IndexPath(row: 99, section: 99)
}
}
extension SettingPickerDelegate {
var currentValue: T {
return self.settingType(index: self.selectedIndexPath.row)!
}
func select(item: T, in tableView: UITableView) {
let index = self.index(settingType: item)
self.tableView(tableView, didSelectRowAtIndexPath: IndexPath(row: index, section: 0))
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let settingType = self.settingType(index: indexPath.row)
assert(settingType != nil)
let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
cell.textLabel?.text = String(describing: settingType!)
cell.accessoryType = indexPath == self.selectedIndexPath ? .checkmark : .none
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if indexPath != self.selectedIndexPath {
if let cell = tableView.cellForRow(at: self.selectedIndexPath) {
cell.accessoryType = .none
}
if let cell = tableView.cellForRow(at: indexPath) {
cell.accessoryType = .checkmark
}
}
self.selectedIndexPath = indexPath
}
}
fileprivate extension SettingPickerDelegate {
func index(settingType: T) -> Int {
for item in self.options {
if item.value == settingType {
return item.index
}
}
return 0
}
func settingType(index: Int) -> T? {
for item in self.options {
if item.index == index {
return item.value
}
}
return nil
}
}
| gpl-3.0 | 0f56671c70683c554a7fff7acc317422 | 28.55 | 100 | 0.61802 | 4.709163 | false | false | false | false |
stevenhuey/Diceware | Diceware/Diceware/DicewareFileGenerator.swift | 1 | 2461 | //
// DicewareFileGenerator.swift
// Diceware
//
// Copyright © 2017 Steve Huey. All rights reserved.
//
import Foundation
class DicewareFileGenerator {
let dicewareFile: String
var words = [String]()
/// Create a `DicewareFileGenerator` instance, loading a wordlist from the
/// text file at the given file path.
///
/// - Parameter dicewareFile: path to a diceware wordlist
init(dicewareFile: String) {
self.dicewareFile = dicewareFile
self.words = loadWords()
}
/// Create a `DicewareFileGenerator` instance from a text file resource
convenience init?(withResource: String, ofType: String) {
if let path = Bundle.main.path(forResource: withResource, ofType: ofType) {
self.init(dicewareFile: path)
} else {
return nil
}
}
/// Return the word from the wordlist at the given index, or nil if the
/// given index is invalid.
///
/// - Parameter value: wordlist index value
/// - Returns: the word from the wordlist at the given index, or nil if the
/// index is invalid
func word(forValue value: Int) -> String? {
return isValidIndex(value) ? words[value] : nil
}
/// Return a random word from the wordlist
///
/// - Returns: a random word from the wordlist
fileprivate func randomWord() -> String {
let value = Int(arc4random_uniform(UInt32(self.words.count)))
return word(forValue: value)!
}
private func isValidIndex(_ value: Int) -> Bool {
return (value >= 0 && value < words.count)
}
/// Load words from the wordlist file into an `[String]`. Assumes one word
/// per line.
///
/// - Returns: a `[String]` of words from the wordlist file
private func loadWords() -> [String] {
guard let fileData = try? String(contentsOfFile:self.dicewareFile) else {
return []
}
return fileData.components(separatedBy: CharacterSet.newlines)
.map { $0.trimmingCharacters(in: CharacterSet.whitespaces) }
.filter { $0.characters.count > 0 }
}
}
extension DicewareFileGenerator: DicewarePasswordGenerator {
func generatePassword(withNumberOfWords n: Int, separator: String = "-") -> String {
var words = [String]()
for _ in 0 ..< n {
words.append(self.randomWord())
}
return words.joined(separator: separator)
}
}
| mit | 1f22ab75b060b9ccb450ca32b545ea0c | 28.285714 | 87 | 0.620325 | 4.205128 | false | false | false | false |
zhangchn/swelly | swelly/Terminal.swift | 1 | 5629 | //
// Terminal.swift
// swelly
//
// Created by ZhangChen on 05/10/2016.
//
//
import Foundation
protocol TerminalDelegate: NSObjectProtocol {
func didUpdate(in terminal: Terminal)
}
class Terminal {
var offset: Int = 0
var maxRow = GlobalConfig.sharedInstance.row
var maxColumn = GlobalConfig.sharedInstance.column
var cursorColumn = 0
var cursorRow = 0
var grid = [[Cell]]()
var dirty = [[Bool]]()
weak var delegate: TerminalDelegate?
var encoding: Encoding! {
get { return connection!.site.encoding }
set { connection?.site.encoding = newValue }
}
var textBuf : [unichar]
// TODO: observer using notification center
weak var connection: Connection? {
didSet {
if let c = connection {
bbsType = c.site.encoding == .big5 ? .Maple : .Firebird
}
}
}
var bbsType : BBSType = .Firebird
init() {
let cellTemplate = Cell()
for _ in 0..<maxRow {
grid.append([Cell](repeating: cellTemplate, count: maxColumn + 1))
dirty.append([Bool](repeating: false, count: maxColumn + 1))
}
textBuf = [unichar](repeating: 0, count: maxRow * maxColumn + 1)
self.clearAll()
}
func clearAll() {
cursorColumn = 0
cursorRow = 0
var t = Cell.Attribute(rawValue: 0)!
t.fgColor = UInt8(GlobalConfig.sharedInstance.fgColorIndex)
t.bgColor = UInt8(GlobalConfig.sharedInstance.bgColorIndex)
for i in 0..<maxRow {
for j in 0..<maxColumn {
grid[i][j].byte = UInt8(0)
grid[i][j].attribute = t
}
}
setAllDirty()
}
func setAllDirty() {
for i in 0..<maxRow {
for j in 0..<maxColumn {
dirty[i][j] = true
}
}
}
func setDirty(forRow row: Int) {
for j in 0..<maxColumn {
dirty[row][j] = true
}
}
func isDirty(atRow row: Int, column: Int) -> Bool{
return dirty[row][column]
}
func removeAllDirtyMarks() {
for r in 0..<maxRow {
for c in 0..<maxColumn {
dirty[r][c] = false
}
}
}
func attribute(atRow row: Int, column: Int) -> Cell.Attribute {
return grid[row][column].attribute
}
func string(fromIndex:Int, toIndex: Int) -> String? {
var bufLen = 0
var spaceBuf = 0
var firstByte = unichar(0)
for i in fromIndex..<toIndex {
let x = i % maxColumn
let y = i / maxColumn
if x == 0 && i != fromIndex && i - 1 < toIndex {
updateDoubleByteState(for: y)
let cr = unichar(0x000d)
textBuf[bufLen] = cr
bufLen += 1
spaceBuf = 0
}
let db = grid[y][x].attribute.doubleByte
if db == 0 {
if grid[y][x].byte == UInt8(0) || grid[y][x].byte == " ".utf8.first! {
spaceBuf += 1
} else {
for _ in 0..<spaceBuf {
textBuf[bufLen] = " ".utf16.first!
bufLen += 1
}
textBuf[bufLen] = unichar(grid[y][x].byte)
bufLen += 1
spaceBuf = 0
}
} else if db == 1 {
firstByte = unichar(grid[y][x].byte)
} else if db == 2 && firstByte != 0 {
let index = (firstByte << 8) + unichar(grid[y][x].byte) - 0x8000
for _ in 0..<spaceBuf {
textBuf[bufLen] = " ".utf16.first!
bufLen += 1
}
textBuf[bufLen] = decode(index, as: encoding)
bufLen += 1
spaceBuf = 0
}
}
if bufLen == 0 {
return nil
}
return textBuf.withUnsafeBufferPointer {
String(utf16CodeUnits: $0.baseAddress!, count: bufLen)
}
}
func string(atRow row: Int) -> String? {
return string(fromIndex: row * maxColumn, toIndex: maxColumn)
}
func cells(ofRow row: Int) -> [Cell] {
return grid[row]
}
func withCells<R>(ofRow row: Int, block : ([Cell]) -> R) -> R{
return block(grid[row])
}
func cell(atIndex index: Int) -> Cell {
return grid[index / maxColumn][index % maxColumn]
}
func updateDoubleByteState(for row: Int) {
let currentRow = grid[row]
var db = 0
var isDirty = false
for c in 0..<maxColumn {
if db == 0 || db == 2 {
if currentRow[c].byte > 0x7f {
db = 1
if c < maxColumn {
isDirty = dirty[row][c] || dirty[row][c + 1]
dirty[row][c] = isDirty
dirty[row][c+1] = isDirty
}
} else {
db = 0
}
} else {
db = 2
}
grid[row][c].attribute.doubleByte = UInt8(db)
}
}
func feed(grid: inout [[Cell]]) {
for i in 0..<maxRow {
self.grid[i] = grid[i]
}
for i in 0..<maxRow {
updateDoubleByteState(for: i)
}
updateBBSState()
delegate?.didUpdate(in: self)
}
// TODO:
func updateBBSState() {
}
}
| gpl-2.0 | 978025b36c64a191450fb53d95419e14 | 27.866667 | 86 | 0.461894 | 4.160384 | false | false | false | false |
mathcamp/lightbase | Blob.swift | 2 | 1924 | //
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// 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.
//
public class Blob {
public let bytes: [UInt8]
public init(bytes: [UInt8]) {
self.bytes = bytes
}
public convenience init(bytes: UnsafePointer<Void>, length: Int) {
self.init(bytes: [UInt8](UnsafeBufferPointer(
start: UnsafePointer(bytes), count: length
)))
}
public func toHex() -> String {
return bytes.map {
($0 < 16 ? "0" : "") + String($0, radix: 16, uppercase: false)
}.joinWithSeparator("")
}
}
extension Blob : CustomStringConvertible {
public var description: String {
return "x'\(toHex())'"
}
}
extension Blob : Equatable {
}
public func ==(lhs: Blob, rhs: Blob) -> Bool {
return lhs.bytes == rhs.bytes
}
| mit | c1a262d9ab0be2c7b4e63a27919a4c23 | 30.52459 | 80 | 0.688508 | 4.273333 | false | false | false | false |
kickstarter/ios-oss | Library/WKNavigationActionData.swift | 1 | 1183 | import WebKit
public struct WKNavigationActionData {
public let navigationAction: WKNavigationAction
public let navigationType: WKNavigationType
public let request: URLRequest
public let targetFrame: WKFrameInfoData?
public init(navigationAction: WKNavigationAction) {
self.navigationAction = navigationAction
self.navigationType = navigationAction.navigationType
self.request = navigationAction.request
self.targetFrame = navigationAction.targetFrame.map(WKFrameInfoData.init(frameInfo:))
}
internal init(
navigationType: WKNavigationType,
request: URLRequest,
sourceFrame _: WKFrameInfoData,
targetFrame: WKFrameInfoData?
) {
self.navigationAction = WKNavigationAction()
self.navigationType = navigationType
self.request = request
self.targetFrame = targetFrame
}
}
public struct WKFrameInfoData {
public let frameInfo: WKFrameInfo
public let mainFrame: Bool
public init(frameInfo: WKFrameInfo) {
self.frameInfo = frameInfo
self.mainFrame = frameInfo.isMainFrame
}
public init(mainFrame: Bool, request _: URLRequest) {
self.frameInfo = WKFrameInfo()
self.mainFrame = mainFrame
}
}
| apache-2.0 | e36cf3068652a859fc75b8a7404f117d | 27.166667 | 89 | 0.759087 | 5.121212 | false | false | false | false |
algolia/algoliasearch-client-swift | Sources/AlgoliaSearchClient/Models/Places/PlacesQuery.swift | 1 | 3476 | //
// PlacesQuery.swift
//
//
// Created by Vladislav Fitc on 12/04/2020.
//
import Foundation
public struct PlacesQuery {
/// The query to match places by name.
public var query: String?
/// Restrict the search results to a specific type.
public var type: PlaceType?
/// If specified, restrict the search results to a specific list of countries.
/// - Engine default: Search on the whole planet.
public var countries: [Country]?
/// Force to first search around a specific latitude longitude.
public var aroundLatLng: Point?
/// Whether or not to first search around the geolocation of the user found via his IP address.
/// - Engine default: true
public var aroundLatLngViaIP: Bool?
/// Radius in meters to search around the latitude/longitude.
/// Otherwise a default radius is automatically computed given the area density.
public var aroundRadius: AroundRadius?
/// Controls whether the _rankingInfo object should be included in the hits.
/// - Engine default: false
public var getRankingInfo: Bool?
/// Specifies how many results you want to retrieve per search.
/// - Engine default: 20
public var hitsPerPage: Int?
/// Specifies the language of the results.
///
/// When set to nil, engine returns the results in all available languages
/// - Remark: Cannot be set explicitly. To set the language of places query, set the `language` parameter of `PlaceClients.search` method.
/// - Engine default: nil
internal var language: Language?
public init(_ query: String? = nil) {
self.query = query
}
}
extension PlacesQuery: Builder {}
extension PlacesQuery: ExpressibleByStringInterpolation {
public init(stringLiteral value: String) {
self.init(value)
}
}
extension PlacesQuery: Codable {
enum CodingKeys: String, CodingKey {
case query
case type
case countries
case aroundLatLng
case aroundLatLngViaIP
case aroundRadius
case getRankingInfo
case hitsPerPage
case language
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
query = try container.decodeIfPresent(forKey: .query)
type = try container.decodeIfPresent(forKey: .type)
countries = try container.decodeIfPresent(forKey: .countries)
aroundLatLng = try container.decodeIfPresent(forKey: .aroundLatLng)
aroundLatLngViaIP = try container.decodeIfPresent(forKey: .aroundLatLngViaIP)
aroundRadius = try container.decodeIfPresent(forKey: .aroundRadius)
getRankingInfo = try container.decodeIfPresent(forKey: .getRankingInfo)
hitsPerPage = try container.decodeIfPresent(forKey: .hitsPerPage)
language = try container.decodeIfPresent(forKey: .language)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(query, forKey: .query)
try container.encodeIfPresent(type, forKey: .type)
try container.encodeIfPresent(countries, forKey: .countries)
try container.encodeIfPresent(aroundLatLng, forKey: .aroundLatLng)
try container.encodeIfPresent(aroundLatLngViaIP, forKey: .aroundLatLngViaIP)
try container.encodeIfPresent(aroundRadius, forKey: .aroundRadius)
try container.encodeIfPresent(getRankingInfo, forKey: .getRankingInfo)
try container.encodeIfPresent(hitsPerPage, forKey: .hitsPerPage)
try container.encodeIfPresent(language, forKey: .language)
}
}
| mit | 2eee6abee0868f4746f94f56d25e2eff | 32.423077 | 140 | 0.739931 | 4.462131 | false | false | false | false |
cristianames/shopping-tracker | shopping-tracker/UIComponent/MainViewController.swift | 1 | 2205 | //
// MainViewController.swift
// shopping-tracker
//
// Created by Cristian Ames on 2/12/17.
// Copyright © 2017 Cristian Ames. All rights reserved.
//
import UIKit
public class MainViewController: UITabBarController {
override public func viewDidLoad() {
super.viewDidLoad()
delegate = self
let controllers = createTabs()
self.viewControllers = controllers
selectedIndex = 1
// Do any additional setup after loading the view.
}
override public func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
}
extension MainViewController: UITabBarControllerDelegate {
public func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
print("Should select viewController: \(viewController.title) ?")
return true;
}
}
fileprivate func createTabs() -> [UIViewController] {
let myItems = MyItemsViewController(viewModel: MyItemsViewModel())
let myItemsIcon = UITabBarItem(title: "MyItems",
image: UIImage(identifier: .bagInactive),
selectedImage: UIImage(identifier: .bagActive))
myItems.tabBarItem = myItemsIcon
let market = MarketViewController(viewModel: MarketViewModel())
let marketIcon = UITabBarItem(title: "Market",
image: UIImage(identifier: .marketInactive),
selectedImage: UIImage(identifier: .marketActive))
market.tabBarItem = marketIcon
let shoppingCart = ShoppingCartViewController(viewModel: ShoppingCartViewModel())
let shoppingCartIcon = UITabBarItem(title: "Shopping Cart",
image: UIImage(identifier: .shoppingCartInactive),
selectedImage: UIImage(identifier: .shoppingCartActive))
shoppingCart.tabBarItem = shoppingCartIcon
return [myItems, market, shoppingCart]
}
| mit | a9053035ed8aeb5761883978064bc103 | 33.4375 | 129 | 0.650635 | 5.636829 | false | false | false | false |
siromathu/SMButton | SMButton.swift | 1 | 4623 | //
// SMButton.swift
// Sample
//
// Created by Siroson Mathuranga Sivarajah on 26/12/16.
// Copyright © 2016 Siroson Mathuranga Sivarajah. All rights reserved.
//
let checkMark = "✓"
let errorMark = "✕"
import UIKit
class SMButton: UIButton, Shakeable {
// MARK: - Types
enum Status {
case start, failed, success
}
var updateStatus = Status.start {
didSet {
switch updateStatus {
case .start:
startActivity()
case .failed:
endActivity(title: errorMark, isFailed: true)
case .success:
endActivity(title: checkMark, isFailed: false)
}
}
}
// MARK:- Properties
private var buttontitleLabel = UILabel()
private var activityIndicator: UIActivityIndicatorView!
public var title: String! {
didSet {
buttontitleLabel.text = title
}
}
// MARK:- Initializers
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init(frame: CGRect, title: String) {
self.init(frame: frame)
layer.cornerRadius = 5.0
backgroundColor = #colorLiteral(red: 0.3486660123, green: 0.6849880219, blue: 0.3210497797, alpha: 1)
self.title = title
// add controls
setTitleLabel()
setActivityIndicator()
}
override func setTitle(_ title: String?, for state: UIControlState) {
super.setTitle("", for: .normal)
self.title = title
}
// MARK: - Conveniance Methods
private func setTitleLabel() {
buttontitleLabel = UILabel(frame: self.bounds)
buttontitleLabel.isUserInteractionEnabled = false
buttontitleLabel.font = UIFont.systemFont(ofSize: 20.0)
buttontitleLabel.textColor = .white
buttontitleLabel.textAlignment = .center
buttontitleLabel.backgroundColor = .clear
buttontitleLabel.text = self.title
addSubview(buttontitleLabel)
}
private func setActivityIndicator() {
activityIndicator = UIActivityIndicatorView()
activityIndicator.isUserInteractionEnabled = false
let xPos = bounds.size.width/2
let yPos = bounds.size.height + bounds.size.height/2
activityIndicator.center = CGPoint(x: xPos, y: yPos)
addSubview(activityIndicator)
}
func startActivity() {
self.backgroundColor = #colorLiteral(red: 0.3486660123, green: 0.6849880219, blue: 0.3210497797, alpha: 1)
activityIndicator.startAnimating()
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: {
self.buttontitleLabel.frame.origin.y = -self.frame.size.height
let xPos = self.bounds.size.width/2;
let yPos = self.bounds.size.height/2;
self.activityIndicator.center = CGPoint(x: xPos, y: yPos);
}, completion: nil)
}
func endActivity(title: String, isFailed: Bool) {
self.buttontitleLabel.text = title
self.buttontitleLabel.frame.origin.y = self.frame.size.height
UIView.animate(withDuration: 0.3, delay: 0, options: .curveEaseIn, animations: {
if isFailed {
self.backgroundColor = .red
}
self.buttontitleLabel.frame.origin.y = 0
self.activityIndicator.center.y = -(self.bounds.size.height + self.bounds.size.height/2)
}, completion: { finished in
self.activityIndicator.stopAnimating()
let xPos = self.bounds.size.width/2
let yPos = self.bounds.size.height + self.bounds.size.height/2
self.activityIndicator.center = CGPoint(x: xPos, y: yPos)
if isFailed {
self.shake()
}
})
}
}
// MARK: - Protocols
protocol Shakeable {
func shake()
}
extension Shakeable where Self: UIView {
func shake() {
let animation = CABasicAnimation(keyPath: "position")
animation.duration = 0.05
animation.repeatCount = 5
animation.autoreverses = true
animation.fromValue = NSValue(cgPoint: CGPoint(x: self.center.x - 4.0, y: self.center.y))
animation.toValue = NSValue(cgPoint: CGPoint(x: self.center.x + 4.0, y: self.center.y))
layer.add(animation, forKey: "position")
}
}
| mit | b89f2a73bdff72b8b6a98e192b3992af | 29.993289 | 114 | 0.592464 | 4.348399 | false | false | false | false |
bsmith11/ScoreReporter | ScoreReporter/Settings/Acknowledgement List/AcknowledgementListViewController.swift | 1 | 3182 | //
// AcknowledgementListViewController.swift
// ScoreReporter
//
// Created by Bradley Smith on 10/4/16.
// Copyright © 2016 Brad Smith. All rights reserved.
//
import UIKit
import Anchorage
import ScoreReporterCore
class AcknowledgementListViewController: UIViewController, MessageDisplayable {
fileprivate let dataSource: AcknowledgementListDataSource
fileprivate let tableView = UITableView(frame: .zero, style: .plain)
override var topLayoutGuide: UILayoutSupport {
configureMessageView(super.topLayoutGuide)
return messageLayoutGuide
}
init(dataSource: AcknowledgementListDataSource) {
self.dataSource = dataSource
super.init(nibName: nil, bundle: nil)
title = "Acknowledgements"
let backButton = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
navigationItem.backBarButtonItem = backButton
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func loadView() {
view = UIView()
configureViews()
configureLayout()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
deselectRows(in: tableView, animated: animated)
}
}
// MARK: - Private
private extension AcknowledgementListViewController {
func configureViews() {
tableView.dataSource = self
tableView.delegate = self
tableView.register(cellClass: SettingsCell.self)
tableView.estimatedRowHeight = 70.0
tableView.rowHeight = UITableViewAutomaticDimension
tableView.backgroundColor = UIColor.white
tableView.separatorStyle = .none
tableView.alwaysBounceVertical = true
view.addSubview(tableView)
}
func configureLayout() {
tableView.edgeAnchors == edgeAnchors
}
}
// MARK: - UITableViewDataSource
extension AcknowledgementListViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return dataSource.numberOfSections()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.numberOfItems(in: section)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueCell(for: indexPath) as SettingsCell
let item = dataSource.item(at: indexPath)
cell.configure(with: item?.title)
cell.separatorHidden = indexPath.item == 0
return cell
}
}
// MARK: - UITableViewDelegate
extension AcknowledgementListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
guard let item = dataSource.item(at: indexPath) else {
return
}
let acknowledgementViewController = AcknowledgementViewController(acknowledgement: item)
navigationController?.pushViewController(acknowledgementViewController, animated: true)
}
}
| mit | 4bbfde0f9653b8766cb5b0b7b1c362f5 | 28.183486 | 100 | 0.702924 | 5.465636 | false | true | false | false |
omochi/numsw | Playgrounds/sandbox/sandbox/ViewController.swift | 1 | 1330 | //
// ViewController.swift
// sandbox
//
// Created by sonson on 2017/03/04.
// Copyright © 2017年 sonson. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func onRightButton(sender: UIButton) {
let vc = RendererDebugViewController()
present(vc, animated: true)
}
@IBAction func onLeftButton(_ sender: Any) {
func makeRenderer() -> ChartRenderer {
let points1 = DummyData.points1()
let points2 = DummyData.points2()
var chart = Chart()
chart.elements = [
.line(LineGraph(points: points1)),
.line(LineGraph(points: points2))
]
chart.computeViewport()
return ChartRenderer(chart: chart)
}
let vc = RenderScrollViewController()
vc.append(renderer: makeRenderer())
vc.append(renderer: makeRenderer())
vc.append(renderer: makeRenderer())
present(vc, animated: true)
}
@IBAction func onTestButton(sender: UIButton) {
DummyData.runHoldExample()
present(NumswPlayground.shared.viewController, animated: true)
}
}
| mit | 002b29e5bd2829fbfab7863b72e3c712 | 25.019608 | 70 | 0.57046 | 4.689046 | false | false | false | false |
apple/swift-experimental-string-processing | Sources/_RegexParser/Regex/Parse/Sema.swift | 1 | 15132 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
/// Validate a regex AST for semantic validity. Once bytecode is emitted at
/// compile time, this could potentially be subsumed by the bytecode generator.
fileprivate struct RegexValidator {
let ast: AST
let captures: CaptureList
var diags = Diagnostics()
init(_ ast: AST) {
self.ast = ast
self.captures = ast.captureList
}
mutating func error(_ kind: ParseError, at loc: SourceLocation) {
diags.error(kind, at: loc)
}
mutating func unreachable(_ str: String, at loc: SourceLocation) {
diags.fatal(.unreachable(str), at: loc)
}
}
extension String {
fileprivate var quoted: String { "'\(self)'" }
}
extension RegexValidator {
mutating func validate() -> AST {
for opt in ast.globalOptions?.options ?? [] {
validateGlobalMatchingOption(opt)
}
validateCaptures()
validateNode(ast.root)
var result = ast
result.diags.append(contentsOf: diags)
return result
}
/// Called when some piece of invalid AST is encountered. We want to ensure
/// an error was emitted.
mutating func expectInvalid(at loc: SourceLocation) {
guard ast.diags.hasAnyError else {
unreachable("Invalid, but no error emitted?", at: loc)
return
}
}
mutating func validateGlobalMatchingOption(_ opt: AST.GlobalMatchingOption) {
switch opt.kind {
case .limitDepth, .limitHeap, .limitMatch, .notEmpty, .notEmptyAtStart,
.noAutoPossess, .noDotStarAnchor, .noJIT, .noStartOpt, .utfMode,
.unicodeProperties:
// These are PCRE specific, and not something we're likely to ever
// support.
error(.unsupported("global matching option"), at: opt.location)
case .newlineMatching:
// We have implemented the correct behavior for multi-line literals, but
// these should also affect '.' and '\N' matching, which we haven't
// implemented.
error(.unsupported("newline matching mode"), at: opt.location)
case .newlineSequenceMatching:
// We haven't yet implemented the '\R' matching specifics of these.
error(.unsupported("newline sequence matching mode"), at: opt.location)
}
}
mutating func validateCaptures() {
// TODO: Should this be validated when creating the capture list?
var usedNames = Set<String>()
for capture in captures.captures {
guard let name = capture.name else { continue }
if !usedNames.insert(name).inserted {
error(.duplicateNamedCapture(name), at: capture.location)
}
}
}
mutating func validateReference(_ ref: AST.Reference) {
if let recLevel = ref.recursionLevel {
error(.unsupported("recursion level"), at: recLevel.location)
}
switch ref.kind {
case .absolute(let num):
guard let i = num.value else {
// Should have already been diagnosed.
expectInvalid(at: ref.innerLoc)
break
}
if i >= captures.captures.count {
error(.invalidReference(i), at: ref.innerLoc)
}
case .named(let name):
// An empty name is already invalid, so don't bother validating.
guard !name.isEmpty else { break }
if !captures.hasCapture(named: name) {
error(.invalidNamedReference(name), at: ref.innerLoc)
}
case .relative(let num):
guard let _ = num.value else {
// Should have already been diagnosed.
expectInvalid(at: ref.innerLoc)
break
}
error(.unsupported("relative capture reference"), at: ref.innerLoc)
}
}
mutating func validateMatchingOption(_ opt: AST.MatchingOption) {
let loc = opt.location
switch opt.kind {
case .allowDuplicateGroupNames:
// Not currently supported as we need to figure out what to do with
// the capture type.
error(.unsupported("duplicate group naming"), at: loc)
case .unicodeWordBoundaries:
error(.unsupported("unicode word boundary mode"), at: loc)
case .textSegmentWordMode, .textSegmentGraphemeMode:
error(.unsupported("text segment mode"), at: loc)
case .byteSemantics:
error(.unsupported("byte semantic mode"), at: loc)
case .unicodeScalarSemantics:
error(.unsupported("unicode scalar semantic mode"), at: loc)
case .graphemeClusterSemantics:
error(.unsupported("grapheme semantic mode"), at: loc)
case .caseInsensitive, .possessiveByDefault, .reluctantByDefault,
.singleLine, .multiline, .namedCapturesOnly, .extended, .extraExtended,
.asciiOnlyDigit, .asciiOnlyWord, .asciiOnlySpace, .asciiOnlyPOSIXProps:
break
}
}
mutating func validateMatchingOptions(_ opts: AST.MatchingOptionSequence) {
for opt in opts.adding {
validateMatchingOption(opt)
}
for opt in opts.removing {
validateMatchingOption(opt)
}
}
mutating func validateBinaryProperty(
_ prop: Unicode.BinaryProperty, at loc: SourceLocation
) {
switch prop {
case .asciiHexDigit, .alphabetic, .bidiControl, .bidiMirrored, .cased,
.caseIgnorable, .changesWhenCasefolded, .changesWhenCasemapped,
.changesWhenNFKCCasefolded, .changesWhenLowercased,
.changesWhenTitlecased, .changesWhenUppercased, .dash, .deprecated,
.defaultIgnorableCodePoint, .diacratic, .extender,
.fullCompositionExclusion, .graphemeBase, .graphemeExtended, .hexDigit,
.idContinue, .ideographic, .idStart, .idsBinaryOperator,
.idsTrinaryOperator, .joinControl, .logicalOrderException, .lowercase,
.math, .noncharacterCodePoint, .patternSyntax, .patternWhitespace,
.quotationMark, .radical, .regionalIndicator, .softDotted,
.sentenceTerminal, .terminalPunctuation, .unifiedIdiograph, .uppercase,
.variationSelector, .whitespace, .xidContinue, .xidStart:
break
case .emojiModifierBase, .emojiModifier, .emoji, .emojiPresentation:
// These are available on macOS 10.12.2, iOS 10.2, tvOS 10.1, watchOS 3.1.1.
// TODO: We should ideally check deployment target for such conditionally
// available properties.
break
case .expandsOnNFC, .expandsOnNFD, .expandsOnNFKD, .expandsOnNFKC:
error(.deprecatedUnicode(prop.rawValue.quoted), at: loc)
case .compositionExclusion, .emojiComponent,
.extendedPictographic, .graphemeLink, .hyphen, .otherAlphabetic,
.otherDefaultIgnorableCodePoint, .otherGraphemeExtended,
.otherIDContinue, .otherIDStart, .otherLowercase, .otherMath,
.otherUppercase, .prependedConcatenationMark:
error(.unsupported(prop.rawValue.quoted), at: loc)
}
}
mutating func validateCharacterProperty(
_ prop: AST.Atom.CharacterProperty, at loc: SourceLocation
) {
// TODO: We could re-add the .other case to diagnose unknown properties
// here instead of in the parser.
// TODO: Should we store an 'inner location' for the contents of `\p{...}`?
switch prop.kind {
case .binary(let b, _):
validateBinaryProperty(b, at: loc)
case .any, .assigned, .ascii, .generalCategory, .posix, .named, .script,
.scriptExtension, .age, .numericType, .numericValue, .mapping, .ccc:
break
case .invalid:
// Should have already been diagnosed.
expectInvalid(at: loc)
case .pcreSpecial:
error(.unsupported("PCRE property"), at: loc)
case .block:
error(.unsupported("Unicode block property"), at: loc)
case .javaSpecial:
error(.unsupported("Java property"), at: loc)
}
}
mutating func validateEscaped(
_ esc: AST.Atom.EscapedBuiltin, at loc: SourceLocation
) {
switch esc {
case .resetStartOfMatch, .singleDataUnit, .trueAnychar,
// '\N' needs to be emitted using 'emitDot'.
.notNewline:
error(.unsupported("'\\\(esc.character)'"), at: loc)
// Character classes.
case .decimalDigit, .notDecimalDigit, .whitespace, .notWhitespace,
.wordCharacter, .notWordCharacter, .graphemeCluster,
.horizontalWhitespace, .notHorizontalWhitespace,
.verticalTab, .notVerticalTab:
break
case .newlineSequence:
break
// Assertions.
case .wordBoundary, .notWordBoundary, .startOfSubject,
.endOfSubjectBeforeNewline, .endOfSubject, .textSegment,
.notTextSegment, .firstMatchingPositionInSubject:
break
// Literal escapes.
case .alarm, .backspace, .escape, .formfeed, .newline, .carriageReturn,
.tab:
break
}
}
mutating func validateAtom(_ atom: AST.Atom, inCustomCharacterClass: Bool) {
switch atom.kind {
case .escaped(let esc):
validateEscaped(esc, at: atom.location)
case .keyboardControl, .keyboardMeta, .keyboardMetaControl:
// We need to implement the scalar computations for these.
error(.unsupported("control sequence"), at: atom.location)
case .property(let p):
validateCharacterProperty(p, at: atom.location)
case .backreference(let r):
validateReference(r)
case .subpattern:
error(.unsupported("subpattern"), at: atom.location)
case .callout:
// These are PCRE and Oniguruma specific, supporting them is future work.
error(.unsupported("callout"), at: atom.location)
case .backtrackingDirective:
// These are PCRE-specific, and are unlikely to be fully supported.
error(.unsupported("backtracking directive"), at: atom.location)
case .changeMatchingOptions(let opts):
validateMatchingOptions(opts)
case .namedCharacter:
// TODO: We should error on unknown Unicode scalar names.
break
case .scalarSequence:
// Not currently supported in a custom character class.
if inCustomCharacterClass {
error(.unsupported("scalar sequence in custom character class"),
at: atom.location)
}
case .char, .scalar, .caretAnchor, .dollarAnchor, .dot:
break
case .invalid:
// Should have already been diagnosed.
expectInvalid(at: atom.location)
break
}
}
mutating func validateCustomCharacterClass(_ c: AST.CustomCharacterClass) {
for member in c.members {
validateCharacterClassMember(member)
}
}
mutating func validateCharacterClassRange(
_ range: AST.CustomCharacterClass.Range
) {
let lhs = range.lhs
let rhs = range.rhs
validateAtom(lhs, inCustomCharacterClass: true)
validateAtom(rhs, inCustomCharacterClass: true)
guard lhs.isValidCharacterClassRangeBound else {
error(.invalidCharacterClassRangeOperand, at: lhs.location)
return
}
guard rhs.isValidCharacterClassRangeBound else {
error(.invalidCharacterClassRangeOperand, at: rhs.location)
return
}
guard let lhsChar = lhs.literalCharacterValue else {
error(
.unsupported("character class range operand"), at: lhs.location)
return
}
guard let rhsChar = rhs.literalCharacterValue else {
error(
.unsupported("character class range operand"), at: rhs.location)
return
}
if lhsChar > rhsChar {
error(
.invalidCharacterRange(from: lhsChar, to: rhsChar), at: range.dashLoc)
}
}
mutating func validateCharacterClassMember(
_ member: AST.CustomCharacterClass.Member
) {
switch member {
case .custom(let c):
validateCustomCharacterClass(c)
case .range(let r):
validateCharacterClassRange(r)
case .atom(let a):
validateAtom(a, inCustomCharacterClass: true)
case .setOperation(let lhs, _, let rhs):
for lh in lhs { validateCharacterClassMember(lh) }
for rh in rhs { validateCharacterClassMember(rh) }
case .quote, .trivia:
break
}
}
mutating func validateGroup(_ group: AST.Group) {
let kind = group.kind
if let name = kind.value.name, name.isEmpty {
expectInvalid(at: kind.location)
}
switch kind.value {
case .capture, .namedCapture, .nonCapture, .lookahead, .negativeLookahead,
.atomicNonCapturing:
break
case .balancedCapture:
// These are .NET specific, and kinda niche.
error(.unsupported("balanced capture"), at: kind.location)
case .nonCaptureReset:
// We need to figure out how these interact with typed captures.
error(.unsupported("branch reset group"), at: kind.location)
case .nonAtomicLookahead:
error(.unsupported("non-atomic lookahead"), at: kind.location)
case .lookbehind, .negativeLookbehind, .nonAtomicLookbehind:
error(.unsupported("lookbehind"), at: kind.location)
case .scriptRun, .atomicScriptRun:
error(.unsupported("script run"), at: kind.location)
case .changeMatchingOptions(let opts):
validateMatchingOptions(opts)
}
validateNode(group.child)
}
mutating func validateQuantification(_ quant: AST.Quantification) {
validateNode(quant.child)
if !quant.child.isQuantifiable {
error(.notQuantifiable, at: quant.child.location)
}
switch quant.amount.value {
case .range(let lhs, let rhs):
guard let lhs = lhs.value, let rhs = rhs.value else {
// Should have already been diagnosed.
expectInvalid(at: quant.location)
break
}
if lhs > rhs {
error(.invalidQuantifierRange(lhs, rhs), at: quant.location)
}
case .zeroOrMore, .oneOrMore, .zeroOrOne, .exactly, .nOrMore, .upToN:
break
}
}
mutating func validateNode(_ node: AST.Node) {
switch node {
case .alternation(let a):
for branch in a.children {
validateNode(branch)
}
case .concatenation(let c):
for child in c.children {
validateNode(child)
}
case .group(let g):
validateGroup(g)
case .conditional(let c):
// Note even once we get runtime support for this, we need to change the
// parsing to incorporate what is specified in the syntax proposal.
error(.unsupported("conditional"), at: c.location)
case .quantification(let q):
validateQuantification(q)
case .atom(let a):
validateAtom(a, inCustomCharacterClass: false)
case .customCharacterClass(let c):
validateCustomCharacterClass(c)
case .absentFunction(let a):
// These are Oniguruma specific.
error(.unsupported("absent function"), at: a.location)
case .interpolation(let i):
// This is currently rejected in the parser for better diagnostics, but
// reject here too until we get runtime support.
error(.unsupported("interpolation"), at: i.location)
case .quote, .trivia, .empty:
break
}
}
}
/// Check a regex AST for semantic validity.
public func validate(_ ast: AST) -> AST {
var validator = RegexValidator(ast)
return validator.validate()
}
| apache-2.0 | 704d3868418c6d535cae1b09ce74e963 | 31.541935 | 82 | 0.666799 | 4.225635 | false | false | false | false |
alankarmisra/SwiftCircularIconButtonWithProgressBar | Example/SwiftCircularIconButtonWithProgressBar/ViewController.swift | 1 | 2430 | //
// ViewController.swift
// SwiftCircularIconButtonWithProgressBar
//
// Created by Alankar Misra on 06/01/2016.
// Copyright (c) 2016 Alankar Misra. All rights reserved.
//
/* Credits:
The Example uses icons created by lastspark and useiconic.com from the Noun Project.
*/
import UIKit
import SwiftCircularIconButtonWithProgressBar
class ViewController: UIViewController {
@IBOutlet var btn: SwiftCircularIconButtonWithProgressBar!
let iconStart = UIImage(named:"iconStart")
let iconPause = UIImage(named:"iconPause")
let iconDone = UIImage(named:"iconDone")
var timer:NSTimer!
override func viewDidLoad() {
super.viewDidLoad()
setIconToStart()
btn.iconInset = 0.35
btn.setTitle("", forState: .Normal)
btn.resetProgress() // Set progress to 0 but without animation
btn.icon = iconStart
btn.tag = 0 // tags: 0 = start, 1 = pause, 2 = done
}
@IBAction func didTapBtn(sender: AnyObject) {
switch btn.tag {
case 0:
// Start progress simulation
btn.animatesOffsets = false
timer?.invalidate()
setIconToPause()
timer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(updateProgressAction), userInfo: nil, repeats: true)
case 1:
// Pause progress simulation
timer?.invalidate()
btn.tag = 0
setIconToStart()
default:
// The simulation is done. Ignore the tap and wait for it to revert to the start state.
break
}
}
func updateProgressAction() {
btn.progress += 0.1
if btn.progress >= 1.0 {
timer.invalidate()
setIconToDone()
NSTimer.scheduledTimerWithTimeInterval(2.0, target: self, selector: #selector(resetProgress), userInfo: nil, repeats: false)
}
}
func resetProgress() {
timer.invalidate()
btn.progress = 0
setIconToStart()
}
private func setIconToStart() {
btn.tag = 0
btn.icon = iconStart
btn.iconXOffset = 4
}
private func setIconToPause() {
btn.tag = 1
btn.icon = iconPause
btn.iconXOffset = 0
}
private func setIconToDone() {
btn.tag = 2
btn.icon = iconDone
btn.iconXOffset = 0
}
}
| mit | 7ebc1cc7b37e391642475b76a3002ebc | 26.931034 | 150 | 0.599177 | 4.450549 | false | false | false | false |
Sadmansamee/quran-ios | Quran/GappedAudioFilesDownloader.swift | 1 | 1988 | //
// GappedAudioFilesDownloader.swift
// Quran
//
// Created by Mohamed Afifi on 5/14/16.
// Copyright © 2016 Quran.com. All rights reserved.
//
import Foundation
class GappedAudioFilesDownloader: DefaultAudioFilesDownloader {
let downloader: DownloadManager
var request: Request? = nil
init(downloader: DownloadManager) {
self.downloader = downloader
}
func filesForQari(_ qari: Qari,
startAyah: AyahNumber,
endAyah: AyahNumber) -> [(remoteURL: URL, destination: String, resumeURL: String)] {
guard case AudioType.gapped = qari.audioType else {
fatalError("Unsupported qari type gapless. Only gapless qaris can be downloaded here.")
}
var files:[(remoteURL: URL, destination: String, resumeURL: String)] = []
// add besm Allah for all gapped
files.append(createRequestInfo(qari: qari, sura: 1, ayah: 1))
for sura in startAyah.sura...endAyah.sura {
let startAyahNumber = sura == startAyah.sura ? startAyah.ayah : 1
let endAyahNumber = sura == endAyah.sura ? endAyah.ayah : Quran.numberOfAyahsForSura(sura)
for ayah in startAyahNumber...endAyahNumber {
files.append(createRequestInfo(qari: qari, sura: sura, ayah: ayah))
}
}
return files
}
fileprivate func createRequestInfo(qari: Qari, sura: Int, ayah: Int) -> (remoteURL: URL, destination: String, resumeURL: String) {
let fileName = String(format: "%03d%03d", sura, ayah)
let remoteURL = qari.audioURL.appendingPathComponent(fileName).appendingPathExtension(Files.audioExtension)
let localURL = qari.path.stringByAppendingPath(fileName).stringByAppendingExtension(Files.audioExtension)
let resumeURL = localURL.stringByAppendingExtension(Files.downloadResumeDataExtension)
return (remoteURL: remoteURL, destination: localURL, resumeURL: resumeURL)
}
}
| mit | 378f6c0e76fdfb5d78f129d0428bbc6d | 35.796296 | 134 | 0.669351 | 4.642523 | false | false | false | false |
akosma/omxplayerios | Movies/Movies/Code/APIConnector.swift | 1 | 6303 | //
// APIConnector.swift
// Movies
//
// Created by Adrian on 25/07/15.
// Copyright (c) 2015 Adrian Kosmaczewski. All rights reserved.
//
import UIKit
import Socket_IO_Client_Swift
enum APIConnectorNotifications : String {
case MovieListReady = "MovieListReady"
case DiskSpaceAvailable = "DiskSpaceAvailable"
case CurrentMovieReceived = "CurrentMovieReceived"
case NoCurrentMoviePlaying = "NoCurrentMoviePlaying"
case MoviePlaying = "MoviePlaying"
case MovieStopped = "MovieStopped"
case CommandSent = "CommandSent"
case DownloadFinished = "DownloadFinished"
}
enum APIConnectorMovieCommands : String {
case Backward30Seconds = "backward"
case Backward10Minutes = "backward10"
case Faster = "faster"
case Forward30Seconds = "forward"
case Forward10Minutes = "forward10"
case Info = "info"
case Pause = "pause"
case Slower = "slower"
case Subtitles = "subtitles"
case VolumeDown = "voldown"
case VolumeUp = "volup"
}
class APIConnector: NSObject {
static let sharedInstance = APIConnector()
let session = NSURLSession.sharedSession()
var baseURLString : String {
get {
if let preference = NSUserDefaults.standardUserDefaults().stringForKey("server_url") {
return preference
}
let result = "http://192.168.1.128:3000"
NSUserDefaults.standardUserDefaults().setObject(result, forKey: "server_url")
return result
}
}
var socket : SocketIOClient?
// This method is required by the action extension, which has a very
// lifetime and does not require the whole infrastructure to be loaded.
func connectAndDownload(url: String) {
socket = SocketIOClient(socketURL: baseURLString)
socket?.on("welcome") { data, ack in
println("socket connected, downloading movie")
self.downloadMovie(url)
}
socket?.connect()
}
func connect() {
socket = SocketIOClient(socketURL: baseURLString)
socket?.on("welcome") { data, ack in
println("socket connected")
}
socket?.on("movies") { data, ack in
println("received 'movies'")
if let responseArray = data,
let responseDictionary = responseArray[0] as? [String : AnyObject],
let movieArray = responseDictionary["response"] as? [String] {
let userInfo : [NSObject : NSArray] = [
"data": movieArray
]
let notif = APIConnectorNotifications.MovieListReady.rawValue
NSNotificationCenter.defaultCenter().postNotificationName(notif,
object: self,
userInfo: userInfo)
}
}
socket?.on("disk") { data, ack in
println("received 'disk'")
if let responseArray = data,
let responseDictionary = responseArray[0] as? [String : AnyObject],
let diskSpace = responseDictionary["response"] as? String {
let userInfo : [NSObject : String] = [
"data": diskSpace
]
let notif = APIConnectorNotifications.DiskSpaceAvailable.rawValue
NSNotificationCenter.defaultCenter().postNotificationName(notif,
object: self,
userInfo: userInfo)
}
}
socket?.on("current_movie") { data, ack in
println("received 'current_movie'")
if let responseArray = data,
let responseDictionary = responseArray[0] as? [String : AnyObject],
let method = responseDictionary["method"] as? String,
let currentMovie = responseDictionary["response"] as? String {
let userInfo : [NSObject : String] = [
"data": currentMovie
]
var notif = APIConnectorNotifications.CurrentMovieReceived.rawValue
if (method == "error") {
notif = APIConnectorNotifications.NoCurrentMoviePlaying.rawValue
}
NSNotificationCenter.defaultCenter().postNotificationName(notif,
object: self,
userInfo: userInfo)
}
}
socket?.on("stop") { data, ack in
println("received 'stop'")
var notif = APIConnectorNotifications.MovieStopped.rawValue
NSNotificationCenter.defaultCenter().postNotificationName(notif,
object: self)
}
socket?.on("download_finished") { data, ack in
println("received 'download_finished'")
if let responseArray = data,
let responseDictionary = responseArray[0] as? [String : AnyObject],
let response = responseDictionary["response"] as? [String : AnyObject] {
var notif = APIConnectorNotifications.DownloadFinished.rawValue
NSNotificationCenter.defaultCenter().postNotificationName(notif,
object: self,
userInfo: response)
}
}
socket?.connect()
}
func getMovieList() {
println("emitting 'movies'")
socket?.emit("movies")
}
func getAvailableDiskSpace() {
println("emitting 'disk'")
socket?.emit("disk")
}
func getCurrentMovie() {
println("emitting 'current_movie'")
socket?.emit("current_movie")
}
func playMovie(movie: String) {
println("emitting 'play \(movie)'")
socket?.emit("play", movie)
}
func sendCommand(command: APIConnectorMovieCommands) {
println("emitting 'command \(command.rawValue)'")
socket?.emit("command", command.rawValue)
}
func stopMovie() {
println("emitting 'stop'")
socket?.emit("stop")
}
func downloadMovie(url: String) {
println("emitting 'download \(url)'")
socket?.emit("download", url)
}
}
| bsd-2-clause | 82a4d5ea6eefa8c4a286b9f809f14e7a | 34.610169 | 98 | 0.56719 | 5.332487 | false | false | false | false |
SanLiangSan/DDProgressView-Swift | DDSwiftDemo/DDProgressView.swift | 1 | 4301 | //
// DDProgressView.swift
// DDSwiftDemo
//
// Created by Tracy on 14-9-24.
// Copyright (c) 2014年 DIDI. All rights reserved.
//
import Foundation
import UIKit
// ------------------------------------
// Extension method
// ------------------------------------
extension NSObject {
func delay(delay:Double, closure:()->()) {
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(delay * Double(NSEC_PER_SEC))
),
dispatch_get_main_queue(), closure)
}
}
// ------------------------------------
// DDProgressView
// ------------------------------------
class DDProgressView : UIView {
let defaultProgressAnimationTime : CFTimeInterval = 0.25
let colorChangeTime : CFTimeInterval = 0.08
var progressLayer : CAGradientLayer = CAGradientLayer()
var progressDuration : CFTimeInterval = 0.0
var progressViewWidth : CGFloat = 0.0
var progressViewHeight : CGFloat = 0.0
var remainMask : CALayer = CALayer()
var colorfulIng : Bool = true
var progress : CGFloat = 0.0
// init
init(frame: CGRect ,bgColor: UIColor) {
super.init(frame: frame)
colorfulIng = true
progressViewWidth = CGRectGetWidth(frame)
progressViewHeight = CGRectGetHeight(frame)
progressDuration = defaultProgressAnimationTime
progress = 0.0
self.addLayer()
}
// Layer
func addLayer() {
progressLayer = self.gradientLayer()
progressLayer.frame = CGRect(x: 0, y: 0, width: progressViewWidth, height: progressViewHeight)
self.layer.addSublayer(progressLayer)
self.perfortmAnimation()
// mask layer
remainMask.frame = CGRect(x: 0, y: 0, width: 0, height: progressViewHeight)
remainMask.backgroundColor = UIColor.blackColor().CGColor
progressLayer.mask = remainMask
}
// gradientLayer
func gradientLayer() -> CAGradientLayer {
var layer = CAGradientLayer()
layer.anchorPoint = CGPoint(x: 0, y: 0.5)
layer.startPoint = CGPoint(x: 0, y: 0.5)
layer.endPoint = CGPoint(x: 1.0, y: 0.5)
//create colors
var colors : Array = []
var hue : CGFloat
for hue = 0; hue <= 360; hue += 5 {
var color : UIColor
color = UIColor(hue: 1.0 * hue / 360, saturation: 1.0, brightness: 1.0, alpha: 1.0)
colors.append(color.CGColor)
}
layer.colors = colors
return layer
}
func setProgress(aProgress:CGFloat) {
delay(0) {
self.progress = min(1, aProgress)
self.progressDuration = self.defaultProgressAnimationTime
self.setNeedsLayout()
}
}
func setProgress(aProgress:CGFloat, seconds: CFTimeInterval, animated: Bool) {
delay(0) {
self.progress = min(1, aProgress)
self.progressDuration = seconds
self.setNeedsLayout()
}
}
func perfortmAnimation() {
var mutable : Array = progressLayer.colors
let lastColor: AnyObject? = mutable.last
mutable.removeLast()
mutable.insert(lastColor!, atIndex: 0)
progressLayer.colors = mutable
var animation : CABasicAnimation = CABasicAnimation(keyPath: "colors")
animation.toValue = mutable
animation.duration = colorChangeTime
animation.removedOnCompletion = true
animation.fillMode = kCAFillModeForwards
animation.delegate = self
progressLayer.addAnimation(animation, forKey: nil)
}
override func layoutSubviews() {
super.layoutSubviews()
CATransaction.begin()
CATransaction.setAnimationDuration(progressDuration)
var maskRect = remainMask.frame
maskRect.size.width = CGRectGetWidth(self.bounds)*self.progress
remainMask.frame = maskRect
CATransaction.commit()
}
override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
if colorfulIng {
self.perfortmAnimation()
}
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
fatalError("init(coder:) has not been implemented")
}
}
| mit | f0ff79c7b0b45645b4f36fcccdab9966 | 30.152174 | 102 | 0.591068 | 4.755531 | false | false | false | false |
justindarc/firefox-ios | Extensions/Today/TodayViewController.swift | 1 | 11007 | /* 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 UIKit
import NotificationCenter
import Shared
import SnapKit
import XCGLogger
private let log = Logger.browserLogger
struct TodayStrings {
static let NewPrivateTabButtonLabel = NSLocalizedString("TodayWidget.NewPrivateTabButtonLabel", tableName: "Today", value: "New Private Tab", comment: "New Private Tab button label")
static let NewTabButtonLabel = NSLocalizedString("TodayWidget.NewTabButtonLabel", tableName: "Today", value: "New Tab", comment: "New Tab button label")
static let GoToCopiedLinkLabel = NSLocalizedString("TodayWidget.GoToCopiedLinkLabel", tableName: "Today", value: "Go to copied link", comment: "Go to link on clipboard")
}
private struct TodayUX {
static let privateBrowsingColor = UIColor(rgb: 0xcf68ff)
static let backgroundHightlightColor = UIColor(white: 216.0/255.0, alpha: 44.0/255.0)
static let linkTextSize: CGFloat = 10.0
static let labelTextSize: CGFloat = 14.0
static let imageButtonTextSize: CGFloat = 14.0
static let copyLinkImageWidth: CGFloat = 23
static let margin: CGFloat = 8
static let buttonsHorizontalMarginPercentage: CGFloat = 0.1
}
@objc (TodayViewController)
class TodayViewController: UIViewController, NCWidgetProviding {
var copiedURL: URL?
fileprivate lazy var newTabButton: ImageButtonWithLabel = {
let imageButton = ImageButtonWithLabel()
imageButton.addTarget(self, action: #selector(onPressNewTab), forControlEvents: .touchUpInside)
imageButton.label.text = TodayStrings.NewTabButtonLabel
let button = imageButton.button
button.setImage(UIImage(named: "new_tab_button_normal")?.withRenderingMode(.alwaysTemplate), for: .normal)
button.setImage(UIImage(named: "new_tab_button_highlight")?.withRenderingMode(.alwaysTemplate), for: .highlighted)
let label = imageButton.label
label.font = UIFont.systemFont(ofSize: TodayUX.imageButtonTextSize)
imageButton.sizeToFit()
return imageButton
}()
fileprivate lazy var newPrivateTabButton: ImageButtonWithLabel = {
let imageButton = ImageButtonWithLabel()
imageButton.addTarget(self, action: #selector(onPressNewPrivateTab), forControlEvents: .touchUpInside)
imageButton.label.text = TodayStrings.NewPrivateTabButtonLabel
let button = imageButton.button
button.setImage(UIImage(named: "new_private_tab_button_normal"), for: .normal)
button.setImage(UIImage(named: "new_private_tab_button_highlight"), for: .highlighted)
let label = imageButton.label
label.tintColor = TodayUX.privateBrowsingColor
label.textColor = TodayUX.privateBrowsingColor
label.font = UIFont.systemFont(ofSize: TodayUX.imageButtonTextSize)
imageButton.sizeToFit()
return imageButton
}()
fileprivate lazy var openCopiedLinkButton: ButtonWithSublabel = {
let button = ButtonWithSublabel()
button.setTitle(TodayStrings.GoToCopiedLinkLabel, for: .normal)
button.addTarget(self, action: #selector(onPressOpenClibpoard), for: .touchUpInside)
// We need to set the background image/color for .Normal, so the whole button is tappable.
button.setBackgroundColor(UIColor.clear, forState: .normal)
button.setBackgroundColor(TodayUX.backgroundHightlightColor, forState: .highlighted)
button.setImage(UIImage(named: "copy_link_icon")?.withRenderingMode(.alwaysTemplate), for: .normal)
button.label.font = UIFont.systemFont(ofSize: TodayUX.labelTextSize)
button.subtitleLabel.font = UIFont.systemFont(ofSize: TodayUX.linkTextSize)
return button
}()
fileprivate lazy var widgetStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .vertical
stackView.alignment = .fill
stackView.spacing = TodayUX.margin / 2
stackView.distribution = UIStackView.Distribution.fill
stackView.layoutMargins = UIEdgeInsets(top: TodayUX.margin, left: TodayUX.margin, bottom: TodayUX.margin, right: TodayUX.margin)
stackView.isLayoutMarginsRelativeArrangement = true
return stackView
}()
fileprivate lazy var buttonStackView: UIStackView = {
let stackView = UIStackView()
stackView.axis = .horizontal
stackView.alignment = .fill
stackView.spacing = 0
stackView.distribution = UIStackView.Distribution.fillEqually
let edge = self.view.frame.size.width * TodayUX.buttonsHorizontalMarginPercentage
stackView.layoutMargins = UIEdgeInsets(top: 0, left: edge, bottom: 0, right: edge)
stackView.isLayoutMarginsRelativeArrangement = true
return stackView
}()
fileprivate var scheme: String {
guard let string = Bundle.main.object(forInfoDictionaryKey: "MozInternalURLScheme") as? String else {
// Something went wrong/weird, but we should fallback to the public one.
return "firefox"
}
return string
}
override func viewDidLoad() {
super.viewDidLoad()
let widgetView: UIView!
self.extensionContext?.widgetLargestAvailableDisplayMode = .compact
let effectView = UIVisualEffectView(effect: UIVibrancyEffect.widgetPrimary())
self.view.addSubview(effectView)
effectView.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
widgetView = effectView.contentView
buttonStackView.addArrangedSubview(newTabButton)
buttonStackView.addArrangedSubview(newPrivateTabButton)
widgetStackView.addArrangedSubview(buttonStackView)
widgetStackView.addArrangedSubview(openCopiedLinkButton)
widgetView.addSubview(widgetStackView)
widgetStackView.snp.makeConstraints { make in
make.edges.equalTo(widgetView)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateCopiedLink()
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
let edge = size.width * TodayUX.buttonsHorizontalMarginPercentage
buttonStackView.layoutMargins = UIEdgeInsets(top: 0, left: edge, bottom: 0, right: edge)
}
func widgetMarginInsets(forProposedMarginInsets defaultMarginInsets: UIEdgeInsets) -> UIEdgeInsets {
return .zero
}
func updateCopiedLink() {
UIPasteboard.general.asyncURL().uponQueue(.main) { res in
if let copiedURL: URL? = res.successValue,
let url = copiedURL {
self.openCopiedLinkButton.isHidden = false
self.openCopiedLinkButton.subtitleLabel.isHidden = SystemUtils.isDeviceLocked()
self.openCopiedLinkButton.subtitleLabel.text = url.absoluteDisplayString
self.copiedURL = url
} else {
self.openCopiedLinkButton.isHidden = true
self.copiedURL = nil
}
}
}
// MARK: Button behaviour
@objc func onPressNewTab(_ view: UIView) {
openContainingApp("?private=false")
}
@objc func onPressNewPrivateTab(_ view: UIView) {
openContainingApp("?private=true")
}
fileprivate func openContainingApp(_ urlSuffix: String = "") {
let urlString = "\(scheme)://open-url\(urlSuffix)"
self.extensionContext?.open(URL(string: urlString)!) { success in
log.info("Extension opened containing app: \(success)")
}
}
@objc func onPressOpenClibpoard(_ view: UIView) {
if let url = copiedURL,
let encodedString = url.absoluteString.escape() {
openContainingApp("?url=\(encodedString)")
}
}
}
extension UIButton {
func setBackgroundColor(_ color: UIColor, forState state: UIControl.State) {
let colorView = UIView(frame: CGRect(width: 1, height: 1))
colorView.backgroundColor = color
UIGraphicsBeginImageContext(colorView.bounds.size)
if let context = UIGraphicsGetCurrentContext() {
colorView.layer.render(in: context)
}
let colorImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.setBackgroundImage(colorImage, for: state)
}
}
class ImageButtonWithLabel: UIView {
lazy var button = UIButton()
lazy var label = UILabel()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
performLayout()
}
func performLayout() {
addSubview(button)
addSubview(label)
button.snp.makeConstraints { make in
make.top.left.centerX.equalTo(self)
}
label.snp.makeConstraints { make in
make.top.equalTo(button.snp.bottom)
make.leading.trailing.bottom.equalTo(self)
}
label.numberOfLines = 1
label.lineBreakMode = .byWordWrapping
label.textAlignment = .center
label.textColor = UIColor.white
}
func addTarget(_ target: AnyObject?, action: Selector, forControlEvents events: UIControl.Event) {
button.addTarget(target, action: action, for: events)
}
}
class ButtonWithSublabel: UIButton {
lazy var subtitleLabel = UILabel()
lazy var label = UILabel()
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
convenience init() {
self.init(frame: .zero)
}
override init(frame: CGRect) {
super.init(frame: frame)
performLayout()
}
fileprivate func performLayout() {
let titleLabel = self.label
self.titleLabel?.removeFromSuperview()
addSubview(titleLabel)
let imageView = self.imageView!
let subtitleLabel = self.subtitleLabel
subtitleLabel.textColor = UIColor.lightGray
self.addSubview(subtitleLabel)
imageView.snp.makeConstraints { make in
make.centerY.left.equalTo(self)
make.width.equalTo(TodayUX.copyLinkImageWidth)
}
titleLabel.snp.makeConstraints { make in
make.left.equalTo(imageView.snp.right).offset(TodayUX.margin)
make.trailing.top.equalTo(self)
}
subtitleLabel.lineBreakMode = .byTruncatingTail
subtitleLabel.snp.makeConstraints { make in
make.bottom.equalTo(self)
make.top.equalTo(titleLabel.snp.bottom)
make.leading.trailing.equalTo(titleLabel)
}
}
override func setTitle(_ text: String?, for state: UIControl.State) {
self.label.text = text
super.setTitle(text, for: state)
}
}
| mpl-2.0 | e8c550d63da418e17485fc3ca8d6eb3e | 36.060606 | 186 | 0.681294 | 4.940305 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.