repo_name
stringlengths 6
91
| path
stringlengths 6
999
| copies
stringclasses 283
values | size
stringlengths 1
7
| content
stringlengths 3
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Blog/QuickStartSettings.swift | 1 | 1101 | import Foundation
final class QuickStartSettings {
private let userDefaults: UserDefaults
// MARK: - Init
init(userDefaults: UserDefaults = .standard) {
self.userDefaults = userDefaults
}
// MARK: - Quick Start availability
func isQuickStartAvailable(for blog: Blog) -> Bool {
return blog.isUserCapableOf(.ManageOptions) &&
blog.isUserCapableOf(.EditThemeOptions) &&
!blog.isWPForTeams()
}
// MARK: - User Defaults Storage
func promptWasDismissed(for blog: Blog) -> Bool {
guard let key = promptWasDismissedKey(for: blog) else {
return false
}
return userDefaults.bool(forKey: key)
}
func setPromptWasDismissed(_ value: Bool, for blog: Blog) {
guard let key = promptWasDismissedKey(for: blog) else {
return
}
userDefaults.set(value, forKey: key)
}
private func promptWasDismissedKey(for blog: Blog) -> String? {
let siteID = blog.dotComID?.intValue ?? 0
return "QuickStartPromptWasDismissed-\(siteID)"
}
}
| gpl-2.0 |
algolia/algoliasearch-client-swift | Sources/AlgoliaSearchClient/Index/Index+Answers.swift | 1 | 1366 | //
// Index+Answers.swift
//
//
// Created by Vladislav Fitc on 20/11/2020.
//
import Foundation
public extension Index {
/**
Returns answers that match the query.
- Parameter query: The AnswersQuery used to search.
- Parameter requestOptions: Configure request locally with RequestOptions.
- Parameter completion: Result completion
- Returns: Launched asynchronous operation
*/
@discardableResult func findAnswers(for query: AnswersQuery,
requestOptions: RequestOptions? = nil,
completion: @escaping ResultCallback<SearchResponse>) -> Operation & TransportTask {
let command = Command.Answers.Find(indexName: name, query: query, requestOptions: requestOptions)
return execute(command, completion: completion)
}
/**
Returns answers that match the query.
- Parameter query: The AnswersQuery used to search.
- Parameter requestOptions: Configure request locally with RequestOptions.
- Returns: SearchResponse object
*/
@discardableResult func findAnswers(for query: AnswersQuery,
requestOptions: RequestOptions? = nil) throws -> SearchResponse {
let command = Command.Answers.Find(indexName: name, query: query, requestOptions: requestOptions)
return try execute(command)
}
}
| mit |
alenstudent/AaronPod | AaronPod/SwiftFiles/ReplaceMe.swift | 1 | 54 |
public func sayHelloPod() {
print("hello pod")
} | mit |
kickstarter/ios-oss | Library/ViewModels/EmptyStatesViewModelTests.swift | 1 | 2406 | @testable import KsApi
@testable import Library
import Prelude
import ReactiveExtensions_TestHelpers
import ReactiveSwift
import XCTest
internal final class EmptyStatesViewModelTests: TestCase {
internal let vm: EmptyStatesViewModelType = EmptyStatesViewModel()
internal let notifyDelegateToGoToDiscovery = TestObserver<DiscoveryParams?, Never>()
internal let notifyDelegateToGoToFriends = TestObserver<(), Never>()
internal override func setUp() {
super.setUp()
self.vm.outputs.notifyDelegateToGoToDiscovery.observe(self.notifyDelegateToGoToDiscovery.observer)
self.vm.outputs.notifyDelegateToGoToFriends.observe(self.notifyDelegateToGoToFriends.observer)
}
func testGoToDiscovery_Non_Activity() {
let params = DiscoveryParams.defaults |> DiscoveryParams.lens.sort .~ .magic
self.vm.inputs.configureWith(emptyState: .starred)
self.vm.inputs.viewWillAppear()
self.vm.inputs.mainButtonTapped()
self.notifyDelegateToGoToFriends.assertValueCount(0)
self.notifyDelegateToGoToDiscovery.assertValues([params])
}
func testGoToDiscovery_Activity() {
self.vm.inputs.configureWith(emptyState: .activity)
self.vm.inputs.viewWillAppear()
self.vm.inputs.mainButtonTapped()
self.notifyDelegateToGoToFriends.assertValueCount(0)
self.notifyDelegateToGoToDiscovery.assertValues([nil])
}
func testGoToFriends_SocialNoPledges() {
self.vm.inputs.configureWith(emptyState: .socialNoPledges)
self.vm.inputs.viewWillAppear()
self.vm.inputs.mainButtonTapped()
self.notifyDelegateToGoToFriends.assertValueCount(1)
self.notifyDelegateToGoToDiscovery.assertValueCount(0)
}
func testGoToFriends_SocialDisabled() {
self.vm.inputs.configureWith(emptyState: .socialDisabled)
self.vm.inputs.viewWillAppear()
self.vm.inputs.mainButtonTapped()
self.notifyDelegateToGoToFriends.assertValueCount(1)
self.notifyDelegateToGoToDiscovery.assertValueCount(0)
}
func testMainButtonTapped_TrackingEvents() {
self.vm.inputs.configureWith(emptyState: .activity)
self.vm.inputs.viewWillAppear()
self.vm.inputs.mainButtonTapped()
XCTAssertEqual(["CTA Clicked"], self.segmentTrackingClient.events)
XCTAssertEqual(self.segmentTrackingClient.properties(forKey: "context_page"), ["activity_feed"])
XCTAssertEqual(self.segmentTrackingClient.properties(forKey: "context_cta"), ["discover"])
}
}
| apache-2.0 |
lemberg/connfa-ios | Pods/SwiftDate/Sources/SwiftDate/Formatters/RelativeFormatter/languages/lang_ur.swift | 1 | 5233 | import Foundation
// swiftlint:disable type_name
public class lang_ur: RelativeFormatterLang {
/// Urdu
public static let identifier: String = "ur"
public required init() {}
public func quantifyKey(forValue value: Double) -> RelativeFormatter.PluralForm? {
return (value == 1 ? .one : .other)
}
public var flavours: [String: Any] {
return [
RelativeFormatter.Flavour.long.rawValue: self._long,
RelativeFormatter.Flavour.narrow.rawValue: self._narrow,
RelativeFormatter.Flavour.short.rawValue: self._short
]
}
private var _short: [String: Any] {
return [
"year": [
"previous": "گزشتہ سال",
"current": "اس سال",
"next": "اگلے سال",
"past": "{0} سال پہلے",
"future": "{0} سال میں"
],
"quarter": [
"previous": "گزشتہ سہ ماہی",
"current": "اس سہ ماہی",
"next": "اگلے سہ ماہی",
"past": "{0} سہ ماہی قبل",
"future": "{0} سہ ماہی میں"
],
"month": [
"previous": "پچھلے مہینہ",
"current": "اس مہینہ",
"next": "اگلے مہینہ",
"past": "{0} ماہ قبل",
"future": "{0} ماہ میں"
],
"week": [
"previous": "پچھلے ہفتہ",
"current": "اس ہفتہ",
"next": "اگلے ہفتہ",
"past": "{0} ہفتے پہلے",
"future": "{0} ہفتے میں"
],
"day": [
"previous": "گزشتہ کل",
"current": "آج",
"next": "آئندہ کل",
"past": [
"one": "{0} دن پہلے",
"other": "{0} دنوں پہلے"
],
"future": [
"one": "{0} دن میں",
"other": "{0} دنوں میں"
]
],
"hour": [
"current": "اس گھنٹے",
"past": "{0} گھنٹے پہلے",
"future": "{0} گھنٹے میں"
],
"minute": [
"current": "اس منٹ",
"past": "{0} منٹ پہلے",
"future": "{0} منٹ میں"
],
"second": [
"current": "اب",
"past": "{0} سیکنڈ پہلے",
"future": "{0} سیکنڈ میں"
],
"now": "اب"
]
}
private var _narrow: [String: Any] {
return [
"year": [
"previous": "گزشتہ سال",
"current": "اس سال",
"next": "اگلے سال",
"past": "{0} سال پہلے",
"future": "{0} سال میں"
],
"quarter": [
"previous": "گزشتہ سہ ماہی",
"current": "اس سہ ماہی",
"next": "اگلے سہ ماہی",
"past": "{0} سہ ماہی پہلے",
"future": "{0} سہ ماہی میں"
],
"month": [
"previous": "پچھلے مہینہ",
"current": "اس مہینہ",
"next": "اگلے مہینہ",
"past": "{0} ماہ پہلے",
"future": "{0} ماہ میں"
],
"week": [
"previous": "پچھلے ہفتہ",
"current": "اس ہفتہ",
"next": "اگلے ہفتہ",
"past": [
"one": "{0} ہفتہ پہلے",
"other": "{0} ہفتے پہلے"
],
"future": [
"one": "{0} ہفتہ میں",
"other": "{0} ہفتے میں"
]
],
"day": [
"previous": "گزشتہ کل",
"current": "آج",
"next": "آئندہ کل",
"past": "{0} دن پہلے",
"future": [
"one": "{0} دن میں",
"other": "{0} دنوں میں"
]
],
"hour": [
"current": "اس گھنٹے",
"past": [
"one": "{0} گھنٹہ پہلے",
"other": "{0} گھنٹے پہلے"
],
"future": [
"one": "{0} گھنٹہ میں",
"other": "{0} گھنٹوں میں"
]
],
"minute": [
"current": "اس منٹ",
"past": "{0} منٹ پہلے",
"future": "{0} منٹ میں"
],
"second": [
"current": "اب",
"past": "{0} سیکنڈ پہلے",
"future": "{0} سیکنڈ میں"
],
"now": "اب"
]
}
private var _long: [String: Any] {
return [
"year": [
"previous": "گزشتہ سال",
"current": "اس سال",
"next": "اگلے سال",
"past": "{0} سال پہلے",
"future": "{0} سال میں"
],
"quarter": [
"previous": "گزشتہ سہ ماہی",
"current": "اس سہ ماہی",
"next": "اگلے سہ ماہی",
"past": "{0} سہ ماہی پہلے",
"future": "{0} سہ ماہی میں"
],
"month": [
"previous": "پچھلا مہینہ",
"current": "اس مہینہ",
"next": "اگلا مہینہ",
"past": [
"one": "{0} مہینہ پہلے",
"other": "{0} مہینے پہلے"
],
"future": [
"one": "{0} مہینہ میں",
"other": "{0} مہینے میں"
]
],
"week": [
"previous": "پچھلے ہفتہ",
"current": "اس ہفتہ",
"next": "اگلے ہفتہ",
"past": [
"one": "{0} ہفتہ پہلے",
"other": "{0} ہفتے پہلے"
],
"future": [
"one": "{0} ہفتہ میں",
"other": "{0} ہفتے میں"
]
],
"day": [
"previous": "گزشتہ کل",
"current": "آج",
"next": "آئندہ کل",
"past": [
"one": "{0} دن پہلے",
"other": "{0} دنوں پہلے"
],
"future": [
"one": "{0} دن میں",
"other": "{0} دنوں میں"
]
],
"hour": [
"current": "اس گھنٹے",
"past": [
"one": "{0} گھنٹہ پہلے",
"other": "{0} گھنٹے پہلے"
],
"future": "{0} گھنٹے میں"
],
"minute": [
"current": "اس منٹ",
"past": "{0} منٹ پہلے",
"future": "{0} منٹ میں"
],
"second": [
"current": "اب",
"past": "{0} سیکنڈ پہلے",
"future": "{0} سیکنڈ میں"
],
"now": "اب"
]
}
}
| apache-2.0 |
EclipseSoundscapes/EclipseSoundscapes | EclipseSoundscapes/Features/About/Settings/Sections/Language/LanguageSection.swift | 1 | 486 | //
// LanguageSection.swift
// EclipseSoundscapes
//
// Created by Arlindo on 12/26/20.
// Copyright © 2020 Eclipse Soundscapes. All rights reserved.
//
import Foundation
struct LanguageSection: SettingTextHeaderSection, SettingTextFooterSection {
let footerText: String = localizedString(key: "SettingsLanguageAdditionalInstructions")
let headerText: String = localizedString(key: "SettingsLanguageSectionTitle")
let items: [SettingItem] = [LanguageSettingItem()]
}
| gpl-3.0 |
ewhitley/CDAKit | CDAKit/health-data-standards/swift_helpers/CDAKJSONInstantiable.swift | 1 | 679 | //
// CDAKProtocols.swift
// CDAKit
//
// Created by Eric Whitley on 2/16/16.
// Copyright © 2016 Eric Whitley. All rights reserved.
//
import Foundation
///Do not use - will be removed. Was used in HDS Ruby.
internal protocol CDAKJSONInstantiable {
// MARK: - Deprecated - Do not use
///Do not use - will be removed. Was used in HDS Ruby.
init(event: [String:Any?])
}
//this should be removed
// individual classes will handle this, NOT a Ruby-like reflection mechanism
extension CDAKJSONInstantiable {
func initFromEventList(event: [String:Any?]) {
for (key, value) in event {
CDAKUtility.setProperty(self, property: key, value: value)
}
}
}
| mit |
iosdevelopershq/code-challenges | CodeChallenge/Challenges/TwoSum/Entries/juliand665TwoSumEntry.swift | 1 | 1929 | //
// juliand665TwoSumEntry.swift
// CodeChallenge
//
// Created by Julian Dunskus on 06.01.17.
// Copyright © 2017 iosdevelopers. All rights reserved.
//
import Foundation
let juliand665TwoSumEntryNice = CodeChallengeEntry<TwoSumChallenge>(name: "juliand665 (swiftier)", block: findPairNice)
private func findPairNice(in nums: [Int], targeting target: Int) -> (Int, Int)? { // O(log n)
var numbers = nums.enumerated().sorted() { $0.1 < $1.1 } // I assume the closure is making it slower
var i1 = numbers.startIndex
var i2 = numbers.endIndex - 1
// how to C
while true { // solution guaranteed
let n1 = numbers[i1]
let n2 = numbers[i2]
let sum = n1.element + n2.element
if sum == target {
return (n1.offset + 1, n2.offset + 1) // O(1)
} else if sum < target {
i1 += 1
} else {
i2 -= 1
}
}
}
let juliand665TwoSumEntryFast = CodeChallengeEntry<TwoSumChallenge>(name: "juliand665 (swifter)", block: findPairFast)
private func findPairFast(in nums: [Int], targeting target: Int) -> (Int, Int)? { // O(log n)
var numbers = nums.sorted()
var i1 = numbers.startIndex
var i2 = numbers.endIndex - 1
// how to C
while true { // solution guaranteed
let n1 = numbers[i1]
let n2 = numbers[i2]
let sum = n1 + n2
if sum == target {
return (nums.index(of: n1)! + 1, nums.index(of: n2)! + 1) // O(n)
// darn you, indices! sorting .enumerated() instead seems to be slower :(
} else if sum < target {
i1 += 1
} else {
i2 -= 1
}
}
}
let juliand665TwoSumEntryUgly = CodeChallengeEntry<TwoSumChallenge>(name: "juliand665 (hardcoded)", block: findPairUgly)
private func findPairUgly(in nums: [Int], targeting target: Int) -> (Int, Int)? { // O(n)
var first: Int?
for (index, num) in nums.enumerated() {
if num > 2 {
if let first = first {
return (first + 1, index + 1) // why would you not want zero-based indices?
}
first = index
}
}
return nil
}
| mit |
tgyhlsb/RxSwiftExt | Tests/RxSwift/OnceTests.swift | 2 | 2215 | //
// OnceTests.swift
// RxSwiftExtDemo
//
// Created by Florent Pillet on 12/04/16.
// Copyright © 2016 RxSwift Community. All rights reserved.
//
import XCTest
import RxSwift
import RxSwiftExt
import RxTest
class OnceTests: XCTestCase {
func testOnce() {
let onceObservable = Observable.once("Hello")
let scheduler = TestScheduler(initialClock: 0)
let observer1 = scheduler.createObserver(String.self)
_ = onceObservable.subscribe(observer1)
let observer2 = scheduler.createObserver(String.self)
_ = onceObservable.subscribe(observer2)
scheduler.start()
let correct1 = [
next(0, "Hello"),
completed(0)
]
let correct2 : [Recorded<Event<String>>] = [
completed(0)
]
XCTAssertEqual(observer1.events, correct1)
XCTAssertEqual(observer2.events, correct2)
}
func testMultipleOnce() {
let onceObservable1 = Observable.once("Hello")
let onceObservable2 = Observable.once("world")
let scheduler = TestScheduler(initialClock: 0)
let observer1 = scheduler.createObserver(String.self)
_ = onceObservable1.subscribe(observer1)
let observer2 = scheduler.createObserver(String.self)
_ = onceObservable1.subscribe(observer2)
let observer3 = scheduler.createObserver(String.self)
_ = onceObservable2.subscribe(observer3)
let observer4 = scheduler.createObserver(String.self)
_ = onceObservable2.subscribe(observer4)
scheduler.start()
let correct1 = [
next(0, "Hello"),
completed(0)
]
let correct2 : [Recorded<Event<String>>] = [
completed(0)
]
let correct3 = [
next(0, "world"),
completed(0)
]
let correct4 : [Recorded<Event<String>>] = [
completed(0)
]
XCTAssertEqual(observer1.events, correct1)
XCTAssertEqual(observer2.events, correct2)
XCTAssertEqual(observer3.events, correct3)
XCTAssertEqual(observer4.events, correct4)
}
}
| mit |
Urinx/SublimeCode | Sublime/Sublime/Utils/File.swift | 1 | 8746 | //
// File.swift
// Sublime
//
// Created by Eular on 2/18/16.
// Copyright © 2016 Eular. All rights reserved.
//
import UIKit
import Foundation
import Photos
import SSZipArchive
enum FileType {
case Regular, Directory, SymbolicLink, Socket, CharacterSpecial, BlockSpecial, Unknown
}
// MARK: - File Class
class File {
var name = ""
var ext = ""
var path = ""
var url: NSURL
var isDir: Bool = false
var type: FileType = .Unknown
var size: Int = 0
var img: String {
get {
if isDir {
return "folder"
} else if isExistImageResource("file_\(ext)") {
return "file_\(ext)"
} else {
return "file_unknown"
}
}
}
var isImg: Bool {
return (["jpg", "png", "gif"] as NSArray).containsObject(ext)
}
var isAudio: Bool {
return (["mp3"] as NSArray).containsObject(ext)
}
var isVideo: Bool {
return (["mp4", "rmvb", "avi", "flv", "mov"] as NSArray).containsObject(ext)
}
var data: NSData? {
get {
return NSData(contentsOfFile: path)
}
}
var codeLang: String {
let codeLangs = [
"swift": "swift",
"m": "objective-c",
"h": "objective-c",
"c": "c",
"py": "python",
"cpp": "cpp",
"css": "css",
"js": "javascript",
"html": "html",
"htm": "html",
"xml": "xml",
"jsp": "jsp",
// "m": "matlab",
"sh": "shell",
"f90": "fortran",
"java": "java",
"md": "markdown",
"asm": "asm",
"bat": "bat",
"scala": "scala",
"tex": "latex",
"pl": "perl",
"cs": "c-sharp",
"php": "php",
"json": "json",
"yml": "yml",
]
return codeLangs[ext] ?? "txt"
}
let readable: Bool
let writeable: Bool
let executable: Bool
let deleteable: Bool
private let filemgr = NSFileManager.defaultManager()
init(path: String) {
self.path = path
self.name = path.lastPathComponent
self.ext = name.pathExtension
self.url = NSURL(fileURLWithPath: path)
self.readable = filemgr.isReadableFileAtPath(path)
self.writeable = filemgr.isWritableFileAtPath(path)
self.executable = filemgr.isExecutableFileAtPath(path)
self.deleteable = filemgr.isDeletableFileAtPath(path)
do {
let attribs = try filemgr.attributesOfItemAtPath(path)
let filetype = attribs["NSFileType"] as! String
switch filetype {
case "NSFileTypeDirectory":
self.type = .Directory
self.isDir = true
case "NSFileTypeRegular":
self.type = .Regular
case "NSFileTypeSymbolicLink":
self.type = .SymbolicLink
case "NSFileTypeSocket":
self.type = .Socket
case "NSFileTypeCharacterSpecial":
self.type = .CharacterSpecial
case "NSFileTypeBlockSpecial":
self.type = .BlockSpecial
default:
self.type = .Unknown
}
self.size = attribs["NSFileSize"] as! Int
} catch {}
}
func delete() -> Bool {
do {
try filemgr.removeItemAtPath(path)
return true
} catch {
return false
}
}
func read() -> String {
if let data = filemgr.contentsAtPath(path) {
return String(data: data, encoding: NSUTF8StringEncoding) ?? ""
}
return ""
}
func readlines() -> [String] {
return (self.read() ?? "").split("\n")
}
func write(str: String) -> Bool {
do {
try str.writeToFile(path, atomically: true, encoding: NSUTF8StringEncoding)
return true
} catch {
return false
}
}
func write(data: NSData) -> Bool {
return data.writeToFile(path, atomically: true)
}
func append(str: String) -> Bool {
if let handler = NSFileHandle(forUpdatingAtPath: path), let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) {
handler.seekToEndOfFile()
handler.writeData(data)
return true
}
return false
}
func insert(str: String, offset: UInt64) -> Bool {
if let handler = NSFileHandle(forUpdatingAtPath: path), let data = str.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true) {
handler.seekToFileOffset(offset)
let data2 = handler.readDataToEndOfFile()
handler.seekToFileOffset(offset)
handler.writeData(data)
handler.writeData(data2)
return true
}
return false
}
func copy(dest: String) -> Bool {
do {
try filemgr.copyItemAtPath(path, toPath: dest)
return true
} catch {
return false
}
}
func move(dest: String) -> Bool {
do {
try filemgr.moveItemAtPath(path, toPath: dest)
return true
} catch {
return false
}
}
func unzip(destPath: String = "", keepFile: Bool = true) {
if ext == "zip" {
if destPath.isEmpty {
SSZipArchive.unzipFileAtPath(path, toDestination: path.stringByDeletingLastPathComponent)
} else {
SSZipArchive.unzipFileAtPath(path, toDestination: destPath)
}
if !keepFile {
self.delete()
}
} else {
Log("Not zip file")
}
}
static func exist(path: String) -> Bool {
return NSFileManager.defaultManager().fileExistsAtPath(path)
}
}
// MARK: - Folder Class
class Folder: File {
override init(path: String) {
if !File.exist(path) {
let upper = Folder(path: path.stringByDeletingLastPathComponent)
upper.newFolder(path.lastPathComponent)
}
super.init(path: path)
}
func checkFileExist(name: String) -> Bool {
return filemgr.fileExistsAtPath(path.stringByAppendingPathComponent(name))
}
func newFile(name: String) -> Bool {
return filemgr.createFileAtPath(path.stringByAppendingPathComponent(name), contents: nil, attributes: nil)
}
func newFolder(name: String) -> Bool {
do {
try filemgr.createDirectoryAtPath(path.stringByAppendingPathComponent(name), withIntermediateDirectories: true, attributes: nil)
return true
} catch {
return false
}
}
func listFiles() -> [File] {
var fileList = [File]()
do {
let files = try filemgr.contentsOfDirectoryAtPath(path)
for file in files {
let p = path.stringByAppendingPathComponent(file)
var f = File(path: p)
if f.isDir {f = Folder(path: p)}
fileList.append(f)
}
} catch {}
return fileList
}
func saveImage(image: UIImage, name: String, url: NSURL?) {
let imgext = name.pathExtension
switch imgext {
case "png":
if let data = UIImagePNGRepresentation(image) {
data.writeToFile(path.stringByAppendingPathComponent(name), atomically: true)
}
case "jpg":
if let data = UIImageJPEGRepresentation(image, 1) {
data.writeToFile(path.stringByAppendingPathComponent(name), atomically: true)
}
case "gif":
let imgMgr = PHImageManager()
let asset = PHAsset.fetchAssetsWithALAssetURLs([url!], options: nil)[0] as! PHAsset
imgMgr.requestImageDataForAsset(asset, options: nil) { (data, _, _, _) -> Void in
data?.writeToFile(self.path.stringByAppendingPathComponent(name), atomically: true)
}
default: return
}
}
func zip(destPath: String = "") -> File {
var zipPath: String
if destPath.isEmpty {
zipPath = path.stringByDeletingPathExtension.stringByAppendingPathExtension("zip")!
} else {
zipPath = destPath
}
SSZipArchive.createZipFileAtPath(zipPath, withContentsOfDirectory: path)
return File(path: zipPath)
}
}
| gpl-3.0 |
LibraryLoupe/PhotosPlus | PhotosPlus/Cameras/Panasonic/PanasonicLumixDMCGX7.swift | 3 | 531 | //
// Photos Plus, https://github.com/LibraryLoupe/PhotosPlus
//
// Copyright (c) 2016-2017 Matt Klosterman and contributors. All rights reserved.
//
import Foundation
extension Cameras.Manufacturers.Panasonic {
public struct LumixDMCGX7: CameraModel {
public init() {}
public let name = "Panasonic Lumix DMC-GX7"
public let manufacturerType: CameraManufacturer.Type = Cameras.Manufacturers.Panasonic.self
}
}
public typealias PanasonicLumixDMCGX7 = Cameras.Manufacturers.Panasonic.LumixDMCGX7
| mit |
larryhou/swift | SpriteKit/SpriteKit/NinjaActionInfo.swift | 1 | 3483 | //
// NinjaActionInfo.swift
// SpriteKit
//
// Created by larryhou on 24/5/15.
// Copyright (c) 2015 larryhou. All rights reserved.
//
import Foundation
class LayerFrameInfo {
let index: Int
let texture: String
let length: Int
let x, y: Int
let scaleX, scaleY: Double
let rotation: Double
let alpha: Double
init(index: Int, texture: String, length: Int, x: Int, y: Int, scaleX: Double, scaleY: Double, rotation: Double, alpha: Double) {
self.index = index
self.texture = texture
self.length = length
self.x = x
self.y = y
self.scaleX = scaleX
self.scaleY = scaleY
self.rotation = rotation
self.alpha = alpha
}
var position: Int { return index + length }
}
class ActionLayerInfo {
let id: Int
let name: String
var frames: [LayerFrameInfo]
init(id: Int, name: String) {
self.id = id
self.name = name
self.frames = []
}
var length: Int {
var count = 0
for i in 0..<frames.count {
count += frames[i].length
}
return count
}
func decode(data: NSDictionary) {
if data["frame"] == nil {
return
}
let list = data["frame"] as! NSArray
var position: Int = 0
for i in 0..<list.count {
let item = list[i] as! NSDictionary
let index = (item["index"] as! NSString).integerValue
let length = (item["length"] as! NSString).integerValue
var texture: String = ""
var x = 0, y = 0
var scaleX = 1.0, scaleY = 1.0
var rotation = 0.0
var alpha = 1.0
if item["element"] != nil {
let element = (item["element"] as! NSArray)[0] as! NSDictionary
texture = element["filename"] as! String
texture = texture.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
x = (element["x"] as! NSString).integerValue
y = (element["y"] as! NSString).integerValue
scaleX = (element["scaleX"] as! NSString).doubleValue
scaleY = (element["scaleY"] as! NSString).doubleValue
rotation = (element["rotation"] as! NSString).doubleValue
alpha = (element["alpha"] as! NSString).doubleValue
}
let frame = LayerFrameInfo(index: index,
texture: texture,
length: length,
x: x, y: y,
scaleX: scaleX, scaleY: scaleY,
rotation: rotation,
alpha: alpha)
frames.append(frame)
}
}
}
class NinjaActionInfo {
let index: Int
let name: String
var layers: [ActionLayerInfo]
init(index: Int, name: String) {
self.index = index
self.name = name
self.layers = []
}
var length: Int {
var count = 0
for i in 0..<layers.count {
count = max(count, layers[i].length)
}
return count
}
func decode(data: NSDictionary) {
let list = data.valueForKeyPath("layer") as! NSArray
for i in 0..<list.count {
let item = list[i] as! NSDictionary
var layer = ActionLayerInfo(id: (item["id"] as! NSString).integerValue, name: item["name"] as! String)
layer.decode(item)
layers.append(layer)
}
}
}
| mit |
kwizzad/kwizzad-ios | Source/KwizzadAPI.swift | 1 | 9912 | //
// KwizzadAPI.swift
// KwizzadSDK
//
// Created by Fares Ben Hamouda on 21/03/2017.
// Copyright © 2017 Kwizzad. All rights reserved.
//
import Foundation
import RxSwift
class KwizzadAPI {
fileprivate static let MAX_REQUEST_RETRIES = 10;
let model : KwizzadModel;
let disposeBag = DisposeBag();
let sendQueue = PublishSubject<(String, BehaviorSubject<Void>)>();
public init(_ model: KwizzadModel) {
self.model = model;
sendQueue
.flatMap(self.send)
.observeOn(MainScheduler.instance)
.subscribe(onNext: { response in
if(response == "") {
return
}
logger.logMessage("Raw server response: \(response)")
let responseEvents: [FromDict] = dictConvert(str: response)
debugPrint("Response events:", responseEvents)
for responseEvent in responseEvents {
if let noFillEvent = responseEvent as? NoFillEvent {
self.model
.placementModel(placementId: noFillEvent.placementId!)
.transition(from: .REQUESTING_AD,
to: .NOFILL,
beforeChange: { placement in
placement.retryAfter = noFillEvent.retryAfter;
placement.retryInMilliseconds = noFillEvent.retryInMilliseconds;
placement.adResponse = nil;
})
}
if let openTransactionsEvent = responseEvent as? OpenTransactionsEvent {
logger.logMessage("got open transactions \(String(describing: openTransactionsEvent.transactions))");
if let transactions = openTransactionsEvent.transactions {
var newSet : Set<OpenTransaction> = [];
for cb in self.model.openTransactions.value {
if transactions.contains(cb) && (cb.state == .ACTIVE || cb.state == .SENDING) {
newSet.insert(cb);
}
}
newSet.formUnion(transactions)
logger.logMessage("size \(newSet.count)");
if (newSet.count > 0 || newSet.count != self.model.openTransactions.value.count) {
logger.logMessage("changed, setting transactions");
self.model.openTransactions.value = newSet;
// todo
KwizzadSDK.instance.delegate?.kwizzadGotOpenTransactions(
openTransactions: self.model.openTransactions.value
)
}
}
}
if let adResponse = responseEvent as? AdResponseEvent {
self.model.placementModel(placementId: adResponse.placementId!)
.transition(
from: AdState.REQUESTING_AD,
to: AdState.RECEIVED_AD,
beforeChange: { placement in
placement.adResponse = adResponse;
if self.model.overrideWeb != nil, adResponse.url != nil, let regex = try? NSRegularExpression(pattern: "[^:]+://[^/]+", options: .caseInsensitive) {
logger.logMessage("url before \(String(describing: adResponse.url))")
adResponse.url = regex.stringByReplacingMatches(in: adResponse.url!, options: .withTransparentBounds, range: NSMakeRange(0, adResponse.url!.count), withTemplate: self.model.overrideWeb!)
logger.logMessage("url after \(String(describing: adResponse.url))")
}
}
)
}
}
}).addDisposableTo(disposeBag)
}
func isRegardedAsErroneous(response: HTTPURLResponse?) -> Bool {
guard let response = response else { return true; }
let statusCode = response.statusCode;
logger.logMessage("Status code: \(statusCode)")
// Note that we do not handle redirections yet, so we regard them as errors.
return statusCode >= 300;
}
func shouldRetryRequest(response: HTTPURLResponse?) -> Bool {
guard let response = response else { return false; }
let statusCode = response.statusCode;
// 499 is nginx-y for a backend timeout, 500+ is reserved for server-side errors.
// We regard these as retry-able because probably we just have to wait for a backend
// to be available again later.
// Response errors < 499 mean errors on our side, so we won't retry the according requests.
return statusCode >= 499;
}
func retryTimeoutFor(index: Int, error: Swift.Error) -> TimeInterval? {
guard error as? KwizzadSDK.ResponseError == KwizzadSDK.ResponseError.retryableRequestError else {
return nil
}
let retryTimesInMinutes: [Int: TimeInterval] = [0:1.0, 1:5.0, 2:10.0, 3:60.0, 4:360.0, 5: 1440.0]
let timeoutInSeconds = retryTimesInMinutes[min(index, retryTimesInMinutes.count - 1)]! * 60.0
let randomAdditionalTimeout = timeoutInSeconds * Double(arc4random()) / Double(UINT32_MAX)
return 0.5 * timeoutInSeconds + randomAdditionalTimeout
}
func send(_ request: String, _ ret: BehaviorSubject<Void>) -> Observable<String> {
return Observable.create { (observer) -> Disposable in
var task: URLSessionDataTask?
let url = self.model.apiBaseURL(apiKey: self.model.apiKey!) + self.model.apiKey! + "/" + self.model.installId;
let session = URLSession.shared
logger.logMessage("POST \(url): \(request)")
var httpRequest = URLRequest(url: URL(string: url)!)
httpRequest.httpMethod = "POST";
httpRequest.httpBody = request.data(using: .utf8);
logger.logMessage("sending \(String(describing: httpRequest.httpBody))")
httpRequest.setValue("application/json", forHTTPHeaderField: "Content-Type");
task = session.dataTask(with: httpRequest) { (data, response, error) -> Void in
if error != nil {
logger.logMessage("Error while handling HTTP request: \(String(describing: error))")
observer.onError(error!)
return
}
if (self.isRegardedAsErroneous(response: (response as? HTTPURLResponse))) {
let error = (self.shouldRetryRequest(response: response as? HTTPURLResponse)) ? KwizzadSDK.ResponseError.retryableRequestError : KwizzadSDK.ResponseError.fatalError
logger.logMessage("Response had an error (\(error)).")
observer.onError(error)
return
}
let result = String(data: data!, encoding:.utf8)!
logger.logMessage("Response data: \(result)")
observer.onNext(result);
observer.onCompleted()
ret.onCompleted()
}
task?.resume()
return Disposables.create {
if task != nil {
task?.cancel()
}
}
}
.retryWhen { errorObservable -> Observable<Int64> in
return errorObservable.flatMapWithIndex({ (error, index) -> Observable<Int64> in
let seconds = self.retryTimeoutFor(index: index, error: error)
guard seconds != nil && index < KwizzadAPI.MAX_REQUEST_RETRIES else {
return Observable.error(error)
}
logger.logMessage("Retry #\(index) after \(seconds!)s")
return Observable<Int64>.timer(5, scheduler: MainScheduler.instance)
})
}
.catchError { error in
ret.onError(error)
return Observable.just("")
}
}
func convert<T:ToDict>(_ request : [T]) throws -> String {
var str = "[";
var first: Bool = true
for r in request {
if(first) {
first = false;
}
else {
str += ","
}
if let foo : String = dictConvert(r) {
str += foo;
}
}
str += "]"
return str
}
func queue<T:ToDict>(_ request: T...) -> Observable<Void> {
logger.logMessage("queueing \(request)")
do {
let ret = BehaviorSubject<Void>(value: Void())
let r = try convert(request)
sendQueue.onNext((r, ret))
return ret.observeOn(MainScheduler.instance);
}
catch {
return Observable.error(error);
}
}
}
| mit |
belatrix/iOSAllStars | AllStarsV2/AllStarsV2/iPhone/Classes/Events/AboutEvents/AboutEventViewController.swift | 1 | 10516 | //
// AboutEventViewController.swift
// AllStarsV2
//
// Created by Daniel Vasquez Fernandez on 8/29/17.
// Copyright © 2017 Kenyi Rodriguez Vergara. All rights reserved.
//
import UIKit
import EventKit
class AboutEventViewController: UIViewController {
// MARK: - Properties
@IBOutlet weak var lblDetailBody: UILabel!
@IBOutlet weak var lblLocation: UILabel!
@IBOutlet weak var btnAddEvent: UIButton!
let eventStore : EKEventStore = EKEventStore()
var eventExists : Bool = false
var objEvent : EventBE!
var event : EKEvent!
// MARK: - My own methods
func updateEventInfo() {
self.lblDetailBody.text = self.objEvent.event_description
let eventAddress = (self.objEvent.event_address.isEmpty == true) ? "" : ", \(self.objEvent.event_address)"
self.lblLocation.text = "\(self.objEvent.event_location!.location_name)\(eventAddress)" /* Si valor de 'eventAddress' no es vacío, se muestra junto con la coma (,). */
}
func setEventDate() {
self.event = EKEvent(eventStore: self.eventStore)
self.event.title = self.objEvent.event_name
self.event.startDate = self.objEvent.event_datetime
self.event.endDate = self.objEvent.event_datetime.addingTimeInterval(60 * 60)
self.event.notes = self.objEvent.event_description
self.event.calendar = eventStore.defaultCalendarForNewEvents
}
func checkIfEventExists() {
let predicate = eventStore.predicateForEvents(withStart: event.startDate,
end: event.endDate.addingTimeInterval(60 * 60),
calendars: nil)
let existingEvents = eventStore.events(matching: predicate)
for singleEvent in existingEvents {
self.eventExists = (event.title == singleEvent.title && event.startDate == singleEvent.startDate)
let buttonTitle = (self.eventExists == false) ? "Add_to_Calender" : "Remove_from_Calender"
self.btnAddEvent.setTitle(buttonTitle.localized,
for: .normal)
}
}
func addEventToCalender() {
self.setEventDate()
if self.eventExists == false { /* Se va a insertar el evento... */
let differenceBetweenDates = CDMDateManager.calcularDiferenciaDeFechasEntre(self.event.startDate,
conFechaFinal: Date())
if differenceBetweenDates.anios > 0 ||
differenceBetweenDates.meses > 0 ||
differenceBetweenDates.dias > 0 ||
differenceBetweenDates.horas > 0 ||
differenceBetweenDates.minutos > 0 ||
differenceBetweenDates.segundos > 0 { /* El evento ya pasó. No se hace la inserción. */
CDMUserAlerts.showSimpleAlert(title: "older_event_title".localized,
withMessage: "older_event_message".localized,
withAcceptButton: "ok".localized,
withController: self,
withCompletion: nil)
}
else {
do {
try eventStore.save(self.event,
span: EKSpan.thisEvent)
CDMUserAlerts.showSimpleAlert(title: "Event_Added".localized,
withMessage: "Event_added_correctly".localized,
withAcceptButton: "ok".localized,
withController: self,
withCompletion: nil)
self.eventExists = true
UIView.animate(withDuration: 0.3,
animations: {
self.btnAddEvent.setTitle("Remove_from_Calender".localized,
for: .normal)
self.view.layoutIfNeeded()
})
}
catch {
CDMUserAlerts.showSimpleAlert(title: "event_added_error_title".localized,
withMessage: "event_added_error_message".localized,
withAcceptButton: "ok".localized,
withController: self,
withCompletion: nil)
}
}
}
else { /* Se va a eliminar el evento... */
do {
let predicate = eventStore.predicateForEvents(withStart: event.startDate,
end: event.endDate.addingTimeInterval(60 * 60),
calendars: nil)
let existingEvents = eventStore.events(matching: predicate)
for singleEvent in existingEvents{
if event.title == singleEvent.title && event.startDate == singleEvent.startDate {
try self.eventStore.remove(singleEvent, span: .thisEvent)
CDMUserAlerts.showSimpleAlert(title: "Event_Removed".localized,
withMessage: "Event_removed_correctly".localized,
withAcceptButton: "ok".localized,
withController: self, withCompletion: nil)
self.eventExists = false
UIView.animate(withDuration: 0.3, animations: {
self.btnAddEvent.setTitle("Add_to_Calender".localized,
for: .normal)
self.view.layoutIfNeeded()
})
}
}
}
catch {
CDMUserAlerts.showSimpleAlert(title: "event_removed_error_title".localized,
withMessage: "event_removed_error_message".localized,
withAcceptButton: "ok".localized,
withController: self,
withCompletion: nil)
}
}
}
//MARK: - @IBAction/actions methods
@IBAction func btnAddToCalender(_ sender: Any) {
func showAlertForDeniedPermission() {
unowned let viewController = self
DispatchQueue.main.async {
let alert = UIAlertController(title: "Need_Permissions".localized,
message: "permission_use_calendar".localized,
preferredStyle: UIAlertControllerStyle.alert)
let okAction = UIAlertAction(title: "ok".localized,
style: UIAlertActionStyle.default,
handler: { (action) in
guard let profileUrl = URL(string: "App-Prefs:root=AllStarsV2") else { return }
if UIApplication.shared.canOpenURL(profileUrl) {
UIApplication.shared.open(profileUrl,
options: [UIApplicationOpenURLOptionUniversalLinksOnly: false],
completionHandler: nil)
}
})
alert.addAction(okAction)
viewController.present(alert,
animated: true,
completion: nil)
}
}
switch EKEventStore.authorizationStatus(for: .event) {
case .notDetermined:
/* The user has not yet made a choice regarding whether this application may access the service. */
EKEventStore().requestAccess(to: EKEntityType.event,
completion: { [unowned self] (accessGranted, error) in
if accessGranted == true {
self.addEventToCalender()
}
else {
showAlertForDeniedPermission()
}
})
case .denied:
/* The user explicitly denied access to the service for this application. */
showAlertForDeniedPermission()
case .authorized:
/* This application is authorized to access the service. */
self.addEventToCalender()
case .restricted:
/* This application is not authorized to access the service. The user cannot change this application’s status, possibly due to active restrictions such as parental controls being in place. */
CDMUserAlerts.showSimpleAlert(title: "calendar_restricted".localized,
withMessage: "calendar_restricted_message".localized,
withAcceptButton: "ok".localized,
withController: self,
withCompletion: nil)
}
}
//MARK: - AboutEventViewController methods
override func viewDidLoad() {
super.viewDidLoad()
// Configuraciones adicionales.
self.updateEventInfo()
self.setEventDate()
self.checkIfEventExists()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| apache-2.0 |
TonnyTao/HowSwift | how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/Binder.swift | 8 | 1885 | //
// Binder.swift
// RxSwift
//
// Created by Krunoslav Zaher on 9/17/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
/**
Observer that enforces interface binding rules:
* can't bind errors (in debug builds binding of errors causes `fatalError` in release builds errors are being logged)
* ensures binding is performed on a specific scheduler
`Binder` doesn't retain target and in case target is released, element isn't bound.
By default it binds elements on main scheduler.
*/
public struct Binder<Value>: ObserverType {
public typealias Element = Value
private let binding: (Event<Value>) -> Void
/// Initializes `Binder`
///
/// - parameter target: Target object.
/// - parameter scheduler: Scheduler used to bind the events.
/// - parameter binding: Binding logic.
public init<Target: AnyObject>(_ target: Target, scheduler: ImmediateSchedulerType = MainScheduler(), binding: @escaping (Target, Value) -> Void) {
weak var weakTarget = target
self.binding = { event in
switch event {
case .next(let element):
_ = scheduler.schedule(element) { element in
if let target = weakTarget {
binding(target, element)
}
return Disposables.create()
}
case .error(let error):
rxFatalErrorInDebug("Binding error: \(error)")
case .completed:
break
}
}
}
/// Binds next element to owner view as described in `binding`.
public func on(_ event: Event<Value>) {
self.binding(event)
}
/// Erases type of observer.
///
/// - returns: type erased observer.
public func asObserver() -> AnyObserver<Value> {
AnyObserver(eventHandler: self.on)
}
}
| mit |
belatrix/iOSAllStars | AllStarsV2/AllStarsV2/iPhone/Classes/Animations/SeeAllEventsToEventDetailTransition.swift | 1 | 9286 | //
// SeeAllEventsToEventDetailControllerTransition.swift
// AllStarsV2
//
// Created by Javier Siancas Fajardo on 9/26/17.
// Copyright © 2017 Kenyi Rodriguez Vergara. All rights reserved.
//
import UIKit
class SeeAllEventsToEventDetailInteractiveTransition : InteractiveTransition {
var initialScale: CGFloat = 0
@objc func gestureTransitionMethod(_ gesture : UIPanGestureRecognizer){
let view = self.navigationController.view!
if gesture.state == .began {
self.interactiveTransition = UIPercentDrivenInteractiveTransition()
self.navigationController.popViewController(animated: true)
}
else if gesture.state == .changed {
let translation = gesture.translation(in: view)
let delta = fabs(translation.x / view.bounds.width)
self.interactiveTransition?.update(delta)
}
else {
self.interactiveTransition?.finish()
self.interactiveTransition = nil
}
}
}
class SeeAllEventsToEventDetailTransition: ControllerTransition {
override func createInteractiveTransition(navigationController: UINavigationController) -> InteractiveTransition? {
let interactiveTransition = SeeAllEventsToEventDetailInteractiveTransition()
interactiveTransition.navigationController = navigationController
interactiveTransition.gestureTransition = UIPanGestureRecognizer(target: interactiveTransition, action: #selector(interactiveTransition.gestureTransitionMethod(_:)))
interactiveTransition.navigationController.view.addGestureRecognizer(interactiveTransition.gestureTransition!)
return interactiveTransition
}
override func animatePush(toContext context : UIViewControllerContextTransitioning) {
let seeAllEventsViewController = self.controllerOrigin as! SeeAllEventsCategoryViewController
let eventDetailViewController = self.controllerDestination as! EventDetailViewController
let frameForEventImageViewSelected = seeAllEventsViewController.frameForEventImageViewSelected
let containerView = context.containerView
containerView.backgroundColor = .white
let fromView = context.view(forKey: .from)!
fromView.frame = UIScreen.main.bounds
containerView.addSubview(fromView)
let toView = context.view(forKey: .to)!
toView.frame = UIScreen.main.bounds
toView.backgroundColor = .clear
containerView.addSubview(toView)
eventDetailViewController.headerView.alpha = 1.0
seeAllEventsViewController.headerView.alpha = 0.0
eventDetailViewController.eventInformationView.alpha = 0.0
eventDetailViewController.eventInformationBackgroundView.alpha = 0.0
eventDetailViewController.buttonsSectionView.alpha = 0.0
eventDetailViewController.scrollContent.alpha = 0.0
eventDetailViewController.imgEvent.layer.cornerRadius = 8.0
eventDetailViewController.eventInformationBackgroundView.layer.cornerRadius = 8.0
eventDetailViewController.buttonsSectionsViewTopConstraint.constant = 50.0
eventDetailViewController.eventTitleLabelTopConstraint.constant = 58.0
eventDetailViewController.backgroundImageViewLeadingConstraint.constant = frameForEventImageViewSelected!.origin.x
eventDetailViewController.backgroundImageViewTopConstraint.constant = frameForEventImageViewSelected!.origin.y
eventDetailViewController.backgroundImageViewWidthConstraint.constant = frameForEventImageViewSelected!.width
eventDetailViewController.backgroundImageViewHeightConstraint.constant = frameForEventImageViewSelected!.height
containerView.layoutIfNeeded()
eventDetailViewController.view.layoutIfNeeded()
UIView.animate(withDuration: 0.5,
delay: 0,
usingSpringWithDamping: 1.0,
initialSpringVelocity: 0.5,
options: .curveEaseOut,
animations: {
fromView.alpha = 0.0
toView.backgroundColor = .white
eventDetailViewController.eventInformationBackgroundView.layer.cornerRadius = 0.0
eventDetailViewController.imgEvent.layer.cornerRadius = 0.0
eventDetailViewController.backgroundImageViewLeadingConstraint.constant = 0.0
eventDetailViewController.backgroundImageViewTopConstraint.constant = 0.0
eventDetailViewController.backgroundImageViewWidthConstraint.constant = UIScreen.main.bounds.width
eventDetailViewController.backgroundImageViewHeightConstraint.constant = 180.0
eventDetailViewController.view.layoutIfNeeded()
}, completion: nil)
UIView.animate(withDuration: 0.5,
delay: 0.1,
usingSpringWithDamping: 1.0,
initialSpringVelocity: 0.5,
options: .curveEaseOut,
animations: {
eventDetailViewController.headerView.alpha = 1.0
eventDetailViewController.eventInformationBackgroundView.alpha = 1.0
eventDetailViewController.buttonsSectionsViewTopConstraint.constant = 0.0
eventDetailViewController.eventTitleLabelTopConstraint.constant = 8.0
eventDetailViewController.view.layoutIfNeeded()
}, completion: nil)
UIView.animate(withDuration: 0.5,
delay: 0.0,
options: .curveEaseOut,
animations: {
eventDetailViewController.eventInformationView.alpha = 1.0
eventDetailViewController.buttonsSectionView.alpha = 1.0
eventDetailViewController.scrollContent.alpha = 1.0
}) { (_) in
context.completeTransition(true)
}
}
override func animatePop(toContext context : UIViewControllerContextTransitioning) {
let eventDetailViewController = self.controllerOrigin as! EventDetailViewController
let seeAllEventsViewController = self.controllerDestination as! SeeAllEventsCategoryViewController
let frameForEventImageViewSelected = seeAllEventsViewController.frameForEventImageViewSelected
let containerView = context.containerView
containerView.backgroundColor = .white
let toView = context.view(forKey: .to)!
toView.frame = UIScreen.main.bounds
toView.backgroundColor = .white
toView.alpha = 1.0
containerView.addSubview(toView)
let fromView = context.view(forKey: .from)!
fromView.frame = UIScreen.main.bounds
fromView.backgroundColor = .clear
containerView.addSubview(fromView)
eventDetailViewController.headerView.alpha = 0.0
seeAllEventsViewController.headerView.alpha = 1.0
eventDetailViewController.eventInformationView.alpha = 0.0
eventDetailViewController.buttonsSectionView.alpha = 0.0
eventDetailViewController.scrollContent.alpha = 0.0
eventDetailViewController.imgEvent.layer.cornerRadius = 8.0
eventDetailViewController.eventInformationBackgroundView.layer.cornerRadius = 8.0
eventDetailViewController.buttonsSectionsViewTopConstraint.constant = 50.0
eventDetailViewController.eventTitleLabelTopConstraint.constant = 58.0
eventDetailViewController.view.layoutIfNeeded()
UIView.animate(withDuration: 0.6,
delay: 0,
usingSpringWithDamping: 1.0,
initialSpringVelocity: 0.5,
options: .curveEaseOut,
animations: {
eventDetailViewController.eventInformationBackgroundView.alpha = 0.0
eventDetailViewController.backgroundImageViewLeadingConstraint.constant = frameForEventImageViewSelected!.origin.x
eventDetailViewController.backgroundImageViewTopConstraint.constant = frameForEventImageViewSelected!.origin.y
eventDetailViewController.backgroundImageViewWidthConstraint.constant = frameForEventImageViewSelected!.width
eventDetailViewController.backgroundImageViewHeightConstraint.constant = frameForEventImageViewSelected!.height
eventDetailViewController.view.layoutIfNeeded()
}, completion: { (_) in
context.completeTransition(true)
})
}
override func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.6
}
}
| apache-2.0 |
jonesgithub/MLSwiftBasic | MLSwiftBasic/Classes/PhotoBrowser/MLPhotoBrowserPhotoScrollView.swift | 7 | 11580 | //
// MLPhotoBrowserPhotoScrollView.swift
// MLSwiftBasic
//
// Created by 张磊 on 15/8/31.
// Copyright (c) 2015年 MakeZL. All rights reserved.
//
import UIKit
@objc protocol MLPhotoBrowserPhotoScrollViewDelegate: NSObjectProtocol{
func photoBrowserPhotoScrollViewDidSingleClick()
}
class MLPhotoBrowserPhotoScrollView: UIScrollView,MLPhotoBrowserPhotoViewDelegate,MLPhotoPickerBrowserPhotoImageViewDelegate,UIActionSheetDelegate {
var photoImageView:MLPhotoBrowserPhotoImageView?
var isHiddenShowSheet:Bool?
var photo:MLPhotoBrowser?{
willSet{
var thumbImage = newValue!.thumbImage
if (thumbImage == nil) {
self.photoImageView!.image = newValue?.toView?.image
thumbImage = self.photoImageView!.image
}else{
self.photoImageView!.image = thumbImage;
}
self.photoImageView!.contentMode = .ScaleAspectFit;
self.photoImageView!.frame = ZLPhotoRect.setMaxMinZoomScalesForCurrentBoundWithImageView(self.photoImageView!)
// if (self.photoImageView.image == nil) {
// [self setProgress:0.01];
// }
// 网络URL
self.photoImageView?.kf_setImageWithURL(newValue!.photoURL!, placeholderImage: thumbImage, optionsInfo: nil, progressBlock: { (receivedSize, totalSize) -> () in
}, completionHandler: { (image, error, cacheType, imageURL) -> () in
if ((image) != nil) {
self.photoImageView!.image = image
self.displayImage()
}else{
self.photoImageView?.removeScaleBigTap()
}
})
}
}
var sheet:UIActionSheet?
weak var photoScrollViewDelegate:MLPhotoBrowserPhotoScrollViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
self.setupInit()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupInit(){
var tapView = MLPhotoBrowserPhotoView(frame: self.bounds)
tapView.delegate = self
tapView.autoresizingMask = .FlexibleWidth | .FlexibleHeight
tapView.backgroundColor = UIColor.blackColor()
self.addSubview(tapView)
photoImageView = MLPhotoBrowserPhotoImageView(frame: self.bounds)
photoImageView!.delegate = self
photoImageView?.userInteractionEnabled = true
photoImageView!.autoresizingMask = .FlexibleWidth | .FlexibleHeight
photoImageView!.backgroundColor = UIColor.blackColor()
self.addSubview(photoImageView!)
// Setup
self.backgroundColor = UIColor.blackColor()
self.delegate = self
self.showsHorizontalScrollIndicator = false
self.showsVerticalScrollIndicator = false
self.decelerationRate = UIScrollViewDecelerationRateFast
self.autoresizingMask = .FlexibleWidth | .FlexibleHeight;
var longGesture = UILongPressGestureRecognizer(target: self, action: "longGesture:")
self.addGestureRecognizer(longGesture)
}
func displayImage(){
// Reset
self.maximumZoomScale = 1
self.minimumZoomScale = 1
self.zoomScale = 1
self.contentSize = CGSizeMake(0, 0)
// Get image from browser as it handles ordering of fetching
var img = photoImageView?.image
if img != nil {
photoImageView?.hidden = false
// Set ImageView Frame
// Sizes
var boundsSize = self.bounds.size
var imageSize = photoImageView!.image!.size
var xScale = boundsSize.width / imageSize.width; // the scale needed to perfectly fit the image width-wise
var yScale = boundsSize.height / imageSize.height; // the scale needed to perfectly fit the image height-wise
var minScale:CGFloat = min(xScale, yScale);
if (xScale >= 1 && yScale >= 1) {
minScale = min(xScale, yScale);
}
var frameToCenter = CGRectZero;
if (minScale >= 3) {
minScale = 3;
}
photoImageView?.frame = CGRectMake(0, 0, imageSize.width * minScale, imageSize.height * minScale)
self.maximumZoomScale = 3
self.minimumZoomScale = 1.0
self.zoomScale = 1.0
}
self.setNeedsLayout()
}
override func layoutSubviews() {
super.layoutSubviews()
// Center the image as it becomes smaller than the size of the screen
var boundsSize = self.bounds.size
var frameToCenter = photoImageView!.frame
// Horizontally
if (frameToCenter.size.width < boundsSize.width) {
frameToCenter.origin.x = floor((boundsSize.width - frameToCenter.size.width) / 2.0);
} else {
frameToCenter.origin.x = 0;
}
// Vertically
if (frameToCenter.size.height < boundsSize.height) {
frameToCenter.origin.y = floor((boundsSize.height - frameToCenter.size.height) / 2.0);
} else {
frameToCenter.origin.y = 0;
}
// Center
if (!CGRectEqualToRect(photoImageView!.frame, frameToCenter)){
photoImageView!.frame = frameToCenter;
}
}
// MARK:: Tap Detection
func handleDoubleTap(touchPoint:CGPoint){
// Zoom
if (self.zoomScale != self.minimumZoomScale) {
// Zoom out
self.setZoomScale(self.minimumZoomScale, animated: true)
self.contentSize = CGSizeMake(self.frame.size.width, 0)
} else {
// Zoom in to twice the size
var newZoomScale = ((self.maximumZoomScale + self.minimumZoomScale) / 2)
var xsize = self.bounds.size.width / newZoomScale
var ysize = self.bounds.size.height / newZoomScale
self.zoomToRect(CGRectMake(touchPoint.x - xsize/2.0, touchPoint.y - ysize/2, xsize, ysize), animated: true)
}
}
func photoPickerBrowserPhotoViewDoubleTapDetected(touch:UITouch) {
var touchX = touch.locationInView(touch.view).x;
var touchY = touch.locationInView(touch.view).y;
touchX *= 1/self.zoomScale;
touchY *= 1/self.zoomScale;
touchX += self.contentOffset.x;
touchY += self.contentOffset.y;
self.handleDoubleTap(CGPointMake(touchX, touchY))
}
func photoPickerBrowserPhotoImageViewSingleTapDetected(touch: UITouch) {
self.disMissTap(nil)
}
func disMissTap(tap:UITapGestureRecognizer?){
if self.photoScrollViewDelegate?.respondsToSelector("photoBrowserPhotoScrollViewDidSingleClick") == true {
self.photoScrollViewDelegate?.photoBrowserPhotoScrollViewDidSingleClick()
}
}
func longGesture(gesture:UILongPressGestureRecognizer){
if gesture.state == .Began{
if self.isHiddenShowSheet == false{
self.sheet = UIActionSheet(title: "提示", delegate: self, cancelButtonTitle: "取消", destructiveButtonTitle: nil)
self.sheet?.showInView(self)
}
}
}
// Image View
func photoPickerBrowserPhotoImageViewDoubleTapDetected(touch: UITouch) {
self.handleDoubleTap(touch.locationInView(touch.view))
}
func photoPickerBrowserPhotoViewSingleTapDetected(touch: UITouch) {
self.disMissTap(nil)
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return photoImageView
}
func scrollViewDidZoom(scrollView: UIScrollView) {
self.setNeedsLayout()
self.layoutIfNeeded()
}
}
@objc protocol MLPhotoBrowserPhotoViewDelegate: NSObjectProtocol {
func photoPickerBrowserPhotoViewSingleTapDetected(touch:UITouch)
func photoPickerBrowserPhotoViewDoubleTapDetected(touch:UITouch)
}
class MLPhotoBrowserPhotoView: UIView {
var delegate:MLPhotoBrowserPhotoViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
self.addGesture()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addGesture(){
// 双击放大
var scaleBigTap = UITapGestureRecognizer(target: self, action: "handleDoubleTap:")
scaleBigTap.numberOfTapsRequired = 2
scaleBigTap.numberOfTouchesRequired = 1
self.addGestureRecognizer(scaleBigTap)
// 单击缩小
var disMissTap = UITapGestureRecognizer(target: self, action: "handleSingleTap:")
disMissTap.numberOfTapsRequired = 1
disMissTap.numberOfTouchesRequired = 1
self.addGestureRecognizer(disMissTap)
// 只能有一个手势存在
disMissTap.requireGestureRecognizerToFail(scaleBigTap)
}
func handleDoubleTap(touch:UITouch){
if self.delegate?.respondsToSelector("photoPickerBrowserPhotoViewDoubleTapDetected") == false {
self.delegate?.photoPickerBrowserPhotoViewDoubleTapDetected(touch)
}
}
func handleSingleTap(touch:UITouch){
if self.delegate?.respondsToSelector("photoPickerBrowserPhotoViewSingleTapDetected") == false {
self.delegate?.photoPickerBrowserPhotoViewSingleTapDetected(touch)
}
}
}
@objc protocol MLPhotoBrowserPhotoImageViewDelegate: NSObjectProtocol {
func photoPickerBrowserPhotoImageViewSingleTapDetected(touch:UITouch)
func photoPickerBrowserPhotoImageViewDoubleTapDetected(touch:UITouch)
}
class MLPhotoBrowserPhotoImageView: UIImageView {
var scaleBigTap:UITapGestureRecognizer?
var delegate:MLPhotoPickerBrowserPhotoImageViewDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
self.addGesture()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func removeScaleBigTap(){
self.scaleBigTap?.removeTarget(self, action: "handleDoubleTap:")
}
func addGesture(){
// 双击放大
var scaleBigTap = UITapGestureRecognizer(target: self, action: "handleDoubleTap:")
scaleBigTap.numberOfTapsRequired = 2
scaleBigTap.numberOfTouchesRequired = 1
self.addGestureRecognizer(scaleBigTap)
self.scaleBigTap = scaleBigTap
// 单击缩小
var disMissTap = UITapGestureRecognizer(target: self, action: "handleSingleTap:")
disMissTap.numberOfTapsRequired = 1
disMissTap.numberOfTouchesRequired = 1
self.addGestureRecognizer(disMissTap)
// 只能有一个手势存在
disMissTap.requireGestureRecognizerToFail(scaleBigTap)
}
func handleDoubleTap(touch:UITouch){
if self.delegate?.respondsToSelector("photoPickerBrowserPhotoImageViewDoubleTapDetected") == false {
self.delegate?.photoPickerBrowserPhotoImageViewDoubleTapDetected(touch)
}
}
func handleSingleTap(touch:UITouch){
if self.delegate?.respondsToSelector("photoPickerBrowserPhotoImageViewSingleTapDetected") == false {
self.delegate?.photoPickerBrowserPhotoImageViewSingleTapDetected(touch)
}
}
}
| mit |
shajrawi/swift | validation-test/Evolution/test_backward_deploy_always_emit_into_client.swift | 1 | 491 | // RUN: %target-resilience-test --backward-deployment
// REQUIRES: executable_test
// Uses swift-version 4.
// UNSUPPORTED: swift_test_mode_optimize_none_with_implicit_dynamic
import StdlibUnittest
import backward_deploy_always_emit_into_client
var BackwardDeployTopLevelTest = TestSuite("BackwardDeployAlwaysEmitIntoClient")
BackwardDeployTopLevelTest.test("BackwardDeployAlwaysEmitIntoClient") {
expectEqual(serializedFunction(), getVersion() == 1 ? "new" : "old")
}
runAllTests()
| apache-2.0 |
RevenueCat/purchases-ios | Sources/Purchasing/StoreKit2/ProductsFetcherSK2.swift | 1 | 1593 | //
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// ProductsManagerSK2.swift
//
// Created by Andrés Boedo on 7/23/21.
import Foundation
import StoreKit
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
actor ProductsFetcherSK2 {
enum Error: Swift.Error {
case productsRequestError(innerError: Swift.Error)
}
/// - Throws: `ProductsFetcherSK2.Error`
func products(identifiers: Set<String>) async throws -> Set<SK2StoreProduct> {
do {
let storeKitProducts = try await TimingUtil.measureAndLogIfTooSlow(
threshold: .productRequest,
message: Strings.storeKit.sk2_product_request_too_slow
) {
try await StoreKit.Product.products(for: identifiers)
}
Logger.rcSuccess(Strings.storeKit.store_product_request_received_response)
return Set(storeKitProducts.map { SK2StoreProduct(sk2Product: $0) })
} catch {
throw Error.productsRequestError(innerError: error)
}
}
}
@available(iOS 15.0, tvOS 15.0, watchOS 8.0, macOS 12.0, *)
extension ProductsFetcherSK2.Error: CustomNSError {
var errorUserInfo: [String: Any] {
switch self {
case let .productsRequestError(inner):
return [
NSUnderlyingErrorKey: inner
]
}
}
}
| mit |
lucdion/aide-devoir | sources/AideDevoir/Classes/Domain/NetworkStatusController.swift | 1 | 847 | //
// NetworkStatusController.swift
// LuxuryRetreats
//
// Created by Luc Dion on 2016-02-29.
// Copyright © 2016 Mirego. All rights reserved.
//
import AFNetworking
protocol NetworkStatusControllerDelegate: class {
func networkReachabilityStateDidChange(_ isReachable: Bool)
}
class NetworkStatusController {
weak var delegate: NetworkStatusControllerDelegate?
init() {
AFNetworkReachabilityManager.shared().startMonitoring()
AFNetworkReachabilityManager.shared().setReachabilityStatusChange { [weak self] (_) -> Void in
if let strongSelf = self {
strongSelf.delegate?.networkReachabilityStateDidChange(strongSelf.isNetworkReachable())
}
}
}
func isNetworkReachable() -> Bool {
return AFNetworkReachabilityManager.shared().isReachable
}
}
| apache-2.0 |
onevcat/Kingfisher | Tests/KingfisherTests/KingfisherManagerTests.swift | 1 | 46824 | //
// KingfisherManagerTests.swift
// Kingfisher
//
// Created by Wei Wang on 15/10/22.
//
// Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
@testable import Kingfisher
class KingfisherManagerTests: XCTestCase {
var manager: KingfisherManager!
override class func setUp() {
super.setUp()
LSNocilla.sharedInstance().start()
}
override class func tearDown() {
LSNocilla.sharedInstance().stop()
super.tearDown()
}
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
let uuid = UUID()
let downloader = ImageDownloader(name: "test.manager.\(uuid.uuidString)")
let cache = ImageCache(name: "test.cache.\(uuid.uuidString)")
manager = KingfisherManager(downloader: downloader, cache: cache)
manager.defaultOptions = [.waitForCache]
}
override func tearDown() {
LSNocilla.sharedInstance().clearStubs()
clearCaches([manager.cache])
cleanDefaultCache()
manager = nil
super.tearDown()
}
func testRetrieveImage() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
let manager = self.manager!
manager.retrieveImage(with: url) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .none)
manager.retrieveImage(with: url) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .memory)
manager.cache.clearMemoryCache()
manager.retrieveImage(with: url) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .disk)
manager.cache.clearMemoryCache()
manager.cache.clearDiskCache {
manager.retrieveImage(with: url) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .none)
exp.fulfill()
}}}}}
waitForExpectations(timeout: 3, handler: nil)
}
func testRetrieveImageWithProcessor() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
let p = RoundCornerImageProcessor(cornerRadius: 20)
let manager = self.manager!
manager.retrieveImage(with: url, options: [.processor(p)]) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .none)
manager.retrieveImage(with: url) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .none,
"Need a processor to get correct image. Cannot get from cache, need download again.")
manager.retrieveImage(with: url, options: [.processor(p)]) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .memory)
self.manager.cache.clearMemoryCache()
manager.retrieveImage(with: url, options: [.processor(p)]) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .disk)
self.manager.cache.clearMemoryCache()
self.manager.cache.clearDiskCache {
self.manager.retrieveImage(with: url, options: [.processor(p)]) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .none)
exp.fulfill()
}}}}}}
waitForExpectations(timeout: 3, handler: nil)
}
func testRetrieveImageForceRefresh() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
manager.cache.store(
testImage,
original: testImageData,
forKey: url.cacheKey,
processorIdentifier: DefaultImageProcessor.default.identifier,
cacheSerializer: DefaultCacheSerializer.default,
toDisk: true)
{
_ in
XCTAssertTrue(self.manager.cache.imageCachedType(forKey: url.cacheKey).cached)
self.manager.retrieveImage(with: url, options: [.forceRefresh]) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .none)
exp.fulfill()
}
}
waitForExpectations(timeout: 3, handler: nil)
}
func testSuccessCompletionHandlerRunningOnMainQueueDefaultly() {
let progressExpectation = expectation(description: "progressBlock running on main queue")
let completionExpectation = expectation(description: "completionHandler running on main queue")
let url = testURLs[0]
stub(url, data: testImageData, length: 123)
manager.retrieveImage(with: url, options: nil, progressBlock: { _, _ in
XCTAssertTrue(Thread.isMainThread)
progressExpectation.fulfill()})
{
result in
XCTAssertNil(result.error)
XCTAssertTrue(Thread.isMainThread)
completionExpectation.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testShouldNotDownloadImageIfCacheOnlyAndNotInCache() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
manager.retrieveImage(with: url, options: [.onlyFromCache]) { result in
XCTAssertNil(result.value)
XCTAssertNotNil(result.error)
if case .cacheError(reason: .imageNotExisting(let key)) = result.error! {
XCTAssertEqual(key, url.cacheKey)
} else {
XCTFail()
}
exp.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testErrorCompletionHandlerRunningOnMainQueueDefaultly() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData, statusCode: 404)
manager.retrieveImage(with: url) { result in
XCTAssertNotNil(result.error)
XCTAssertTrue(Thread.isMainThread)
XCTAssertTrue(result.error!.isInvalidResponseStatusCode(404))
exp.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testSucessCompletionHandlerRunningOnCustomQueue() {
let progressExpectation = expectation(description: "progressBlock running on custom queue")
let completionExpectation = expectation(description: "completionHandler running on custom queue")
let url = testURLs[0]
stub(url, data: testImageData, length: 123)
let customQueue = DispatchQueue(label: "com.kingfisher.testQueue")
let options: KingfisherOptionsInfo = [.callbackQueue(.dispatch(customQueue))]
manager.retrieveImage(with: url, options: options, progressBlock: { _, _ in
XCTAssertTrue(Thread.isMainThread)
progressExpectation.fulfill()
})
{
result in
XCTAssertNil(result.error)
dispatchPrecondition(condition: .onQueue(customQueue))
completionExpectation.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testLoadCacheCompletionHandlerRunningOnCustomQueue() {
let completionExpectation = expectation(description: "completionHandler running on custom queue")
let url = testURLs[0]
manager.cache.store(testImage, forKey: url.cacheKey)
let customQueue = DispatchQueue(label: "com.kingfisher.testQueue")
manager.retrieveImage(with: url, options: [.callbackQueue(.dispatch(customQueue))]) {
result in
XCTAssertNil(result.error)
dispatchPrecondition(condition: .onQueue(customQueue))
completionExpectation.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testDefaultOptionCouldApply() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
manager.defaultOptions = [.scaleFactor(2)]
manager.retrieveImage(with: url, completionHandler: { result in
#if !os(macOS)
XCTAssertEqual(result.value!.image.scale, 2.0)
#endif
exp.fulfill()
})
waitForExpectations(timeout: 3, handler: nil)
}
func testOriginalImageCouldBeStored() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
let manager = self.manager!
let p = SimpleProcessor()
let options = KingfisherParsedOptionsInfo([.processor(p), .cacheOriginalImage])
let source = Source.network(url)
let context = RetrievingContext(options: options, originalSource: source)
manager.loadAndCacheImage(source: .network(url), context: context) { result in
var imageCached = manager.cache.imageCachedType(forKey: url.cacheKey, processorIdentifier: p.identifier)
var originalCached = manager.cache.imageCachedType(forKey: url.cacheKey)
XCTAssertEqual(imageCached, .memory)
delay(0.1) {
manager.cache.clearMemoryCache()
imageCached = manager.cache.imageCachedType(forKey: url.cacheKey, processorIdentifier: p.identifier)
originalCached = manager.cache.imageCachedType(forKey: url.cacheKey)
XCTAssertEqual(imageCached, .disk)
XCTAssertEqual(originalCached, .disk)
exp.fulfill()
}
}
waitForExpectations(timeout: 3, handler: nil)
}
func testOriginalImageNotBeStoredWithoutOptionSet() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
let p = SimpleProcessor()
let options = KingfisherParsedOptionsInfo([.processor(p), .waitForCache])
let source = Source.network(url)
let context = RetrievingContext(options: options, originalSource: source)
manager.loadAndCacheImage(source: .network(url), context: context) {
result in
var imageCached = self.manager.cache.imageCachedType(forKey: url.cacheKey, processorIdentifier: p.identifier)
var originalCached = self.manager.cache.imageCachedType(forKey: url.cacheKey)
XCTAssertEqual(imageCached, .memory)
XCTAssertEqual(originalCached, .none)
self.manager.cache.clearMemoryCache()
imageCached = self.manager.cache.imageCachedType(forKey: url.cacheKey, processorIdentifier: p.identifier)
originalCached = self.manager.cache.imageCachedType(forKey: url.cacheKey)
XCTAssertEqual(imageCached, .disk)
XCTAssertEqual(originalCached, .none)
exp.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testCouldProcessOnOriginalImage() {
let exp = expectation(description: #function)
let url = testURLs[0]
manager.cache.store(
testImage,
original: testImageData,
forKey: url.cacheKey,
processorIdentifier: DefaultImageProcessor.default.identifier,
cacheSerializer: DefaultCacheSerializer.default,
toDisk: true)
{
_ in
let p = SimpleProcessor()
let cached = self.manager.cache.imageCachedType(forKey: url.cacheKey, processorIdentifier: p.identifier)
XCTAssertFalse(cached.cached)
// No downloading will happen
self.manager.retrieveImage(with: url, options: [.processor(p)]) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .none)
XCTAssertTrue(p.processed)
// The processed image should be cached
let cached = self.manager.cache.imageCachedType(forKey: url.cacheKey, processorIdentifier: p.identifier)
XCTAssertTrue(cached.cached)
exp.fulfill()
}
}
waitForExpectations(timeout: 3, handler: nil)
}
func testFailingProcessOnOriginalImage() {
let exp = expectation(description: #function)
let url = testURLs[0]
manager.cache.store(
testImage,
original: testImageData,
forKey: url.cacheKey,
processorIdentifier: DefaultImageProcessor.default.identifier,
cacheSerializer: DefaultCacheSerializer.default,
toDisk: true)
{
_ in
let p = FailingProcessor()
let cached = self.manager.cache.imageCachedType(forKey: url.cacheKey, processorIdentifier: p.identifier)
XCTAssertFalse(cached.cached)
// No downloading will happen
self.manager.retrieveImage(with: url, options: [.processor(p)]) { result in
XCTAssertNotNil(result.error)
XCTAssertTrue(p.processed)
if case .processorError(reason: .processingFailed(let processor, _)) = result.error! {
XCTAssertEqual(processor.identifier, p.identifier)
} else {
XCTFail()
}
exp.fulfill()
}
}
waitForExpectations(timeout: 3, handler: nil)
}
func testFailingProcessOnDataProviderImage() {
let provider = SimpleImageDataProvider(cacheKey: "key") { .success(testImageData) }
var called = false
let p = FailingProcessor()
let options = [KingfisherOptionsInfoItem.processor(p), .processingQueue(.mainCurrentOrAsync)]
_ = manager.retrieveImage(with: .provider(provider), options: options) { result in
called = true
XCTAssertNotNil(result.error)
if case .processorError(reason: .processingFailed(let processor, _)) = result.error! {
XCTAssertEqual(processor.identifier, p.identifier)
} else {
XCTFail()
}
}
XCTAssertTrue(called)
}
func testCacheOriginalImageWithOriginalCache() {
let exp = expectation(description: #function)
let url = testURLs[0]
let originalCache = ImageCache(name: "test-originalCache")
// Clear original cache first.
originalCache.clearMemoryCache()
originalCache.clearDiskCache {
XCTAssertEqual(originalCache.imageCachedType(forKey: url.cacheKey), .none)
stub(url, data: testImageData)
let p = RoundCornerImageProcessor(cornerRadius: 20)
self.manager.retrieveImage(
with: url,
options: [.processor(p), .cacheOriginalImage, .originalCache(originalCache)])
{
result in
let originalCached = originalCache.imageCachedType(forKey: url.cacheKey)
XCTAssertEqual(originalCached, .disk)
exp.fulfill()
}
}
waitForExpectations(timeout: 5, handler: nil)
}
func testCouldProcessOnOriginalImageWithOriginalCache() {
let exp = expectation(description: #function)
let url = testURLs[0]
let originalCache = ImageCache(name: "test-originalCache")
// Clear original cache first.
originalCache.clearMemoryCache()
originalCache.clearDiskCache {
originalCache.store(
testImage,
original: testImageData,
forKey: url.cacheKey,
processorIdentifier: DefaultImageProcessor.default.identifier,
cacheSerializer: DefaultCacheSerializer.default,
toDisk: true)
{
_ in
let p = SimpleProcessor()
let cached = self.manager.cache.imageCachedType(forKey: url.cacheKey, processorIdentifier: p.identifier)
XCTAssertFalse(cached.cached)
// No downloading will happen
self.manager.retrieveImage(with: url, options: [.processor(p), .originalCache(originalCache)]) {
result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .none)
XCTAssertTrue(p.processed)
// The processed image should be cached
let cached = self.manager.cache.imageCachedType(forKey: url.cacheKey, processorIdentifier: p.identifier)
XCTAssertTrue(cached.cached)
exp.fulfill()
}
}
}
waitForExpectations(timeout: 3, handler: nil)
}
func testCouldProcessDoNotHappenWhenSerializerCachesTheProcessedData() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
let s = DefaultCacheSerializer()
let p1 = SimpleProcessor()
let options1: KingfisherOptionsInfo = [.processor(p1), .cacheSerializer(s), .waitForCache]
let source = Source.network(url)
manager.retrieveImage(with: source, options: options1) { result in
XCTAssertTrue(p1.processed)
let p2 = SimpleProcessor()
let options2: KingfisherOptionsInfo = [.processor(p2), .cacheSerializer(s), .waitForCache]
self.manager.cache.clearMemoryCache()
self.manager.retrieveImage(with: source, options: options2) { result in
XCTAssertEqual(result.value?.cacheType, .disk)
XCTAssertFalse(p2.processed)
exp.fulfill()
}
}
waitForExpectations(timeout: 3, handler: nil)
}
func testCouldProcessAgainWhenSerializerCachesOriginalData() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
var s = DefaultCacheSerializer()
s.preferCacheOriginalData = true
let p1 = SimpleProcessor()
let options1: KingfisherOptionsInfo = [.processor(p1), .cacheSerializer(s), .waitForCache]
let source = Source.network(url)
manager.retrieveImage(with: source, options: options1) { result in
XCTAssertTrue(p1.processed)
let p2 = SimpleProcessor()
let options2: KingfisherOptionsInfo = [.processor(p2), .cacheSerializer(s), .waitForCache]
self.manager.cache.clearMemoryCache()
self.manager.retrieveImage(with: source, options: options2) { result in
XCTAssertEqual(result.value?.cacheType, .disk)
XCTAssertTrue(p2.processed)
exp.fulfill()
}
}
waitForExpectations(timeout: 3, handler: nil)
}
func testWaitForCacheOnRetrieveImage() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
self.manager.retrieveImage(with: url) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .none)
self.manager.cache.clearMemoryCache()
let cached = self.manager.cache.imageCachedType(forKey: url.cacheKey)
XCTAssertEqual(cached, .disk)
exp.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testNotWaitForCacheOnRetrieveImage() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
self.manager.defaultOptions = .empty
self.manager.retrieveImage(with: url, options: [.callbackQueue(.untouch)]) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .none)
// We are not waiting for cache finishing here. So only sync memory cache is done.
XCTAssertEqual(self.manager.cache.imageCachedType(forKey: url.cacheKey), .memory)
// Clear the memory cache.
self.manager.cache.clearMemoryCache()
// After some time, the disk cache should be done.
delay(0.2) {
XCTAssertEqual(self.manager.cache.imageCachedType(forKey: url.cacheKey), .disk)
exp.fulfill()
}
}
waitForExpectations(timeout: 3, handler: nil)
}
func testWaitForCacheOnRetrieveImageWithProcessor() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
let p = RoundCornerImageProcessor(cornerRadius: 20)
self.manager.retrieveImage(with: url, options: [.processor(p)]) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .none)
exp.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testImageShouldOnlyFromMemoryCacheOrRefreshCanBeGotFromMemory() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
manager.retrieveImage(with: url, options: [.fromMemoryCacheOrRefresh]) { result in
// Can be downloaded and cached normally.
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .none)
// Can still be got from memory even when disk cache cleared.
self.manager.cache.clearDiskCache {
self.manager.retrieveImage(with: url, options: [.fromMemoryCacheOrRefresh]) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .memory)
exp.fulfill()
}
}
}
waitForExpectations(timeout: 3, handler: nil)
}
func testImageShouldOnlyFromMemoryCacheOrRefreshCanRefreshIfNotInMemory() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
manager.retrieveImage(with: url, options: [.fromMemoryCacheOrRefresh]) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .none)
XCTAssertEqual(self.manager.cache.imageCachedType(forKey: url.cacheKey), .memory)
self.manager.cache.clearMemoryCache()
XCTAssertEqual(self.manager.cache.imageCachedType(forKey: url.cacheKey), .disk)
// Should skip disk cache and download again.
self.manager.retrieveImage(with: url, options: [.fromMemoryCacheOrRefresh]) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.cacheType, .none)
XCTAssertEqual(self.manager.cache.imageCachedType(forKey: url.cacheKey), .memory)
exp.fulfill()
}
}
waitForExpectations(timeout: 5, handler: nil)
}
func testShouldDownloadAndCacheProcessedImage() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
let size = CGSize(width: 1, height: 1)
let processor = ResizingImageProcessor(referenceSize: size)
manager.retrieveImage(with: url, options: [.processor(processor)]) { result in
// Can download and cache normally
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.image.size, size)
XCTAssertEqual(result.value!.cacheType, .none)
self.manager.cache.clearMemoryCache()
let cached = self.manager.cache.imageCachedType(
forKey: url.cacheKey, processorIdentifier: processor.identifier)
XCTAssertEqual(cached, .disk)
self.manager.retrieveImage(with: url, options: [.processor(processor)]) { result in
XCTAssertNotNil(result.value?.image)
XCTAssertEqual(result.value!.image.size, size)
XCTAssertEqual(result.value!.cacheType, .disk)
exp.fulfill()
}
}
waitForExpectations(timeout: 3, handler: nil)
}
#if os(iOS) || os(tvOS) || os(watchOS)
func testShouldApplyImageModifierWhenDownload() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
var modifierCalled = false
let modifier = AnyImageModifier { image in
modifierCalled = true
return image.withRenderingMode(.alwaysTemplate)
}
manager.retrieveImage(with: url, options: [.imageModifier(modifier)]) { result in
XCTAssertTrue(modifierCalled)
XCTAssertEqual(result.value?.image.renderingMode, .alwaysTemplate)
exp.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testShouldApplyImageModifierWhenLoadFromMemoryCache() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
var modifierCalled = false
let modifier = AnyImageModifier { image in
modifierCalled = true
return image.withRenderingMode(.alwaysTemplate)
}
manager.cache.store(testImage, forKey: url.cacheKey)
manager.retrieveImage(with: url, options: [.imageModifier(modifier)]) { result in
XCTAssertTrue(modifierCalled)
XCTAssertEqual(result.value?.cacheType, .memory)
XCTAssertEqual(result.value?.image.renderingMode, .alwaysTemplate)
exp.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testShouldApplyImageModifierWhenLoadFromDiskCache() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
var modifierCalled = false
let modifier = AnyImageModifier { image in
modifierCalled = true
return image.withRenderingMode(.alwaysTemplate)
}
manager.cache.store(testImage, forKey: url.cacheKey) { _ in
self.manager.cache.clearMemoryCache()
self.manager.retrieveImage(with: url, options: [.imageModifier(modifier)]) { result in
XCTAssertTrue(modifierCalled)
XCTAssertEqual(result.value!.cacheType, .disk)
XCTAssertEqual(result.value!.image.renderingMode, .alwaysTemplate)
exp.fulfill()
}
}
waitForExpectations(timeout: 3, handler: nil)
}
func testImageModifierResultShouldNotBeCached() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
var modifierCalled = false
let modifier = AnyImageModifier { image in
modifierCalled = true
return image.withRenderingMode(.alwaysTemplate)
}
manager.retrieveImage(with: url, options: [.imageModifier(modifier)]) { result in
XCTAssertTrue(modifierCalled)
XCTAssertEqual(result.value?.image.renderingMode, .alwaysTemplate)
let memoryCached = self.manager.cache.retrieveImageInMemoryCache(forKey: url.absoluteString)
XCTAssertNotNil(memoryCached)
XCTAssertEqual(memoryCached?.renderingMode, .automatic)
self.manager.cache.retrieveImageInDiskCache(forKey: url.absoluteString) { result in
XCTAssertNotNil(result.value!)
XCTAssertEqual(result.value??.renderingMode, .automatic)
exp.fulfill()
}
}
waitForExpectations(timeout: 3, handler: nil)
}
#endif
func testRetrieveWithImageProvider() {
let provider = SimpleImageDataProvider(cacheKey: "key") { .success(testImageData) }
var called = false
manager.defaultOptions = .empty
_ = manager.retrieveImage(with: .provider(provider), options: [.processingQueue(.mainCurrentOrAsync)]) {
result in
called = true
XCTAssertNotNil(result.value)
XCTAssertTrue(result.value!.image.renderEqual(to: testImage))
}
XCTAssertTrue(called)
}
func testRetrieveWithImageProviderFail() {
let provider = SimpleImageDataProvider(cacheKey: "key") { .failure(SimpleImageDataProvider.E()) }
var called = false
_ = manager.retrieveImage(with: .provider(provider)) { result in
called = true
XCTAssertNotNil(result.error)
if case .imageSettingError(reason: .dataProviderError(_, let error)) = result.error! {
XCTAssertTrue(error is SimpleImageDataProvider.E)
} else {
XCTFail()
}
}
XCTAssertTrue(called)
}
func testContextRemovingAlternativeSource() {
let allSources: [Source] = [
.network(URL(string: "1")!),
.network(URL(string: "2")!)
]
let info = KingfisherParsedOptionsInfo([.alternativeSources(allSources)])
let context = RetrievingContext(
options: info, originalSource: .network(URL(string: "0")!))
let source1 = context.popAlternativeSource()
XCTAssertNotNil(source1)
guard case .network(let r1) = source1! else {
XCTFail("Should be a network source, but \(source1!)")
return
}
XCTAssertEqual(r1.downloadURL.absoluteString, "1")
let source2 = context.popAlternativeSource()
XCTAssertNotNil(source2)
guard case .network(let r2) = source2! else {
XCTFail("Should be a network source, but \(source2!)")
return
}
XCTAssertEqual(r2.downloadURL.absoluteString, "2")
XCTAssertNil(context.popAlternativeSource())
}
func testRetrievingWithAlternativeSource() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
let brokenURL = URL(string: "brokenurl")!
stub(brokenURL, data: Data())
_ = manager.retrieveImage(
with: .network(brokenURL),
options: [.alternativeSources([.network(url)])])
{
result in
XCTAssertNotNil(result.value)
XCTAssertEqual(result.value!.source.url, url)
XCTAssertEqual(result.value!.originalSource.url, brokenURL)
exp.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testRetrievingErrorsWithAlternativeSource() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: Data())
let brokenURL = URL(string: "brokenurl")!
stub(brokenURL, data: Data())
let anotherBrokenURL = URL(string: "anotherBrokenURL")!
stub(anotherBrokenURL, data: Data())
_ = manager.retrieveImage(
with: .network(brokenURL),
options: [.alternativeSources([.network(anotherBrokenURL), .network(url)])])
{
result in
defer { exp.fulfill() }
XCTAssertNil(result.value)
XCTAssertNotNil(result.error)
guard case .imageSettingError(reason: let reason) = result.error! else {
XCTFail("The error should be image setting error")
return
}
guard case .alternativeSourcesExhausted(let errorInfo) = reason else {
XCTFail("The error reason should be alternativeSourcesFailed")
return
}
XCTAssertEqual(errorInfo.count, 3)
XCTAssertEqual(errorInfo[0].source.url, brokenURL)
XCTAssertEqual(errorInfo[1].source.url, anotherBrokenURL)
XCTAssertEqual(errorInfo[2].source.url, url)
}
waitForExpectations(timeout: 1, handler: nil)
}
func testRetrievingAlternativeSourceTaskUpdateBlockCalled() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
let brokenURL = URL(string: "brokenurl")!
stub(brokenURL, data: Data())
var downloadTaskUpdatedCount = 0
let task = manager.retrieveImage(
with: .network(brokenURL),
options: [.alternativeSources([.network(url)])],
downloadTaskUpdated: { newTask in
downloadTaskUpdatedCount += 1
XCTAssertEqual(newTask?.sessionTask.task.currentRequest?.url, url)
})
{
result in
XCTAssertEqual(downloadTaskUpdatedCount, 1)
exp.fulfill()
}
XCTAssertEqual(task?.sessionTask.task.currentRequest?.url, brokenURL)
waitForExpectations(timeout: 1, handler: nil)
}
func testRetrievingAlternativeSourceCancelled() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
let brokenURL = URL(string: "brokenurl")!
stub(brokenURL, data: Data())
let task = manager.retrieveImage(
with: .network(brokenURL),
options: [.alternativeSources([.network(url)])]
)
{
result in
XCTAssertNotNil(result.error)
XCTAssertTrue(result.error!.isTaskCancelled)
exp.fulfill()
}
task?.cancel()
waitForExpectations(timeout: 1, handler: nil)
}
func testRetrievingAlternativeSourceCanCancelUpdatedTask() {
let exp = expectation(description: #function)
let url = testURLs[0]
let dataStub = delayedStub(url, data: testImageData)
let brokenURL = URL(string: "brokenurl")!
stub(brokenURL, data: Data())
var task: DownloadTask!
task = manager.retrieveImage(
with: .network(brokenURL),
options: [.alternativeSources([.network(url)])],
downloadTaskUpdated: { newTask in
task = newTask
task.cancel()
}
)
{
result in
XCTAssertNotNil(result.error)
XCTAssertTrue(result.error?.isTaskCancelled ?? false)
delay(0.1) {
_ = dataStub.go()
exp.fulfill()
}
}
waitForExpectations(timeout: 1, handler: nil)
}
func testDownsamplingHandleScale2x() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
_ = manager.retrieveImage(
with: .network(url),
options: [.processor(DownsamplingImageProcessor(size: .init(width: 4, height: 4))), .scaleFactor(2)])
{
result in
let image = result.value?.image
XCTAssertNotNil(image)
#if os(macOS)
XCTAssertEqual(image?.size, .init(width: 8, height: 8))
XCTAssertEqual(image?.kf.scale, 1)
#else
XCTAssertEqual(image?.size, .init(width: 4, height: 4))
XCTAssertEqual(image?.kf.scale, 2)
#endif
exp.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testDownsamplingHandleScale3x() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
_ = manager.retrieveImage(
with: .network(url),
options: [.processor(DownsamplingImageProcessor(size: .init(width: 4, height: 4))), .scaleFactor(3)])
{
result in
let image = result.value?.image
XCTAssertNotNil(image)
#if os(macOS)
XCTAssertEqual(image?.size, .init(width: 12, height: 12))
XCTAssertEqual(image?.kf.scale, 1)
#else
XCTAssertEqual(image?.size, .init(width: 4, height: 4))
XCTAssertEqual(image?.kf.scale, 3)
#endif
exp.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testCacheCallbackCoordinatorStateChanging() {
var coordinator = CacheCallbackCoordinator(
shouldWaitForCache: false, shouldCacheOriginal: false)
var called = false
coordinator.apply(.cacheInitiated) {
called = true
}
XCTAssertTrue(called)
XCTAssertEqual(coordinator.state, .done)
coordinator.apply(.cachingImage) { XCTFail() }
XCTAssertEqual(coordinator.state, .done)
coordinator = CacheCallbackCoordinator(
shouldWaitForCache: true, shouldCacheOriginal: false)
called = false
coordinator.apply(.cacheInitiated) { XCTFail() }
XCTAssertEqual(coordinator.state, .idle)
coordinator.apply(.cachingImage) {
called = true
}
XCTAssertTrue(called)
XCTAssertEqual(coordinator.state, .done)
coordinator = CacheCallbackCoordinator(
shouldWaitForCache: false, shouldCacheOriginal: true)
coordinator.apply(.cacheInitiated) {
called = true
}
XCTAssertEqual(coordinator.state, .done)
coordinator.apply(.cachingOriginalImage) { XCTFail() }
XCTAssertEqual(coordinator.state, .done)
coordinator = CacheCallbackCoordinator(
shouldWaitForCache: true, shouldCacheOriginal: true)
coordinator.apply(.cacheInitiated) { XCTFail() }
XCTAssertEqual(coordinator.state, .idle)
coordinator.apply(.cachingOriginalImage) { XCTFail() }
XCTAssertEqual(coordinator.state, .originalImageCached)
coordinator.apply(.cachingImage) { called = true }
XCTAssertEqual(coordinator.state, .done)
coordinator = CacheCallbackCoordinator(
shouldWaitForCache: true, shouldCacheOriginal: true)
coordinator.apply(.cacheInitiated) { XCTFail() }
XCTAssertEqual(coordinator.state, .idle)
coordinator.apply(.cachingImage) { XCTFail() }
XCTAssertEqual(coordinator.state, .imageCached)
coordinator.apply(.cachingOriginalImage) { called = true }
XCTAssertEqual(coordinator.state, .done)
}
func testCallbackClearAfterSuccess() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
var task: DownloadTask?
var called = false
task = manager.retrieveImage(with: url) { result in
XCTAssertFalse(called)
XCTAssertNotNil(result.value?.image)
if !called {
called = true
task?.cancel()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {
exp.fulfill()
}
}
}
waitForExpectations(timeout: 1, handler: nil)
}
func testCanUseCustomizeDefaultCacheSerializer() {
let exp = expectation(description: #function)
let url = testURLs[0]
var cacheSerializer = DefaultCacheSerializer()
cacheSerializer.preferCacheOriginalData = true
manager.cache.store(
testImage,
original: testImageData,
forKey: url.cacheKey,
processorIdentifier: DefaultImageProcessor.default.identifier,
cacheSerializer: cacheSerializer, toDisk: true) {
result in
let computedKey = url.cacheKey.computedKey(with: DefaultImageProcessor.default.identifier)
let fileURL = self.manager.cache.diskStorage.cacheFileURL(forKey: computedKey)
let data = try! Data(contentsOf: fileURL)
XCTAssertEqual(data, testImageData)
exp.fulfill()
}
waitForExpectations(timeout: 1.0)
}
func testCanUseCustomizeDefaultCacheSerializerStoreEncoded() {
let exp = expectation(description: #function)
let url = testURLs[0]
var cacheSerializer = DefaultCacheSerializer()
cacheSerializer.compressionQuality = 0.8
manager.cache.store(
testImage,
original: testImageJEPGData,
forKey: url.cacheKey,
processorIdentifier: DefaultImageProcessor.default.identifier,
cacheSerializer: cacheSerializer, toDisk: true) {
result in
let computedKey = url.cacheKey.computedKey(with: DefaultImageProcessor.default.identifier)
let fileURL = self.manager.cache.diskStorage.cacheFileURL(forKey: computedKey)
let data = try! Data(contentsOf: fileURL)
XCTAssertNotEqual(data, testImageJEPGData)
XCTAssertEqual(data, testImage.kf.jpegRepresentation(compressionQuality: 0.8))
exp.fulfill()
}
waitForExpectations(timeout: 1.0)
}
func testImageResultContainsDataWhenDownloaded() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
manager.retrieveImage(with: url) { result in
XCTAssertNotNil(result.value?.data())
XCTAssertEqual(result.value!.data(), testImageData)
XCTAssertEqual(result.value!.cacheType, .none)
exp.fulfill()
}
waitForExpectations(timeout: 3, handler: nil)
}
func testImageResultContainsDataWhenLoadFromMemoryCache() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
manager.retrieveImage(with: url) { _ in
self.manager.retrieveImage(with: url) { result in
XCTAssertEqual(result.value!.cacheType, .memory)
XCTAssertNotNil(result.value?.data())
XCTAssertEqual(
result.value!.data(),
DefaultCacheSerializer.default.data(with: result.value!.image, original: nil)
)
exp.fulfill()
}
}
waitForExpectations(timeout: 3, handler: nil)
}
func testImageResultContainsDataWhenLoadFromDiskCache() {
let exp = expectation(description: #function)
let url = testURLs[0]
stub(url, data: testImageData)
manager.retrieveImage(with: url) { _ in
self.manager.cache.clearMemoryCache()
self.manager.retrieveImage(with: url) { result in
XCTAssertEqual(result.value!.cacheType, .disk)
XCTAssertNotNil(result.value?.data())
XCTAssertEqual(
result.value!.data(),
DefaultCacheSerializer.default.data(with: result.value!.image, original: nil)
)
exp.fulfill()
}
}
waitForExpectations(timeout: 3, handler: nil)
}
}
class SimpleProcessor: ImageProcessor {
public let identifier = "id"
var processed = false
/// Initialize a `DefaultImageProcessor`
public init() {}
/// Process an input `ImageProcessItem` item to an image for this processor.
///
/// - parameter item: Input item which will be processed by `self`
/// - parameter options: Options when processing the item.
///
/// - returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
processed = true
switch item {
case .image(let image):
return image
case .data(let data):
return KingfisherWrapper<KFCrossPlatformImage>.image(data: data, options: options.imageCreatingOptions)
}
}
}
class FailingProcessor: ImageProcessor {
public let identifier = "FailingProcessor"
var processed = false
public init() {}
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> KFCrossPlatformImage? {
processed = true
return nil
}
}
struct SimpleImageDataProvider: ImageDataProvider {
let cacheKey: String
let provider: () -> (Result<Data, Error>)
func data(handler: @escaping (Result<Data, Error>) -> Void) {
handler(provider())
}
struct E: Error {}
}
| mit |
EBGToo/SBVariables | Sources/Name.swift | 1 | 2657 | //
// Name.swift
// SBVariables
//
// Created by Ed Gamble on 10/22/15.
// Copyright © 2015 Edward B. Gamble Jr. All rights reserved.
//
// See the LICENSE file at the project root for license information.
// See the CONTRIBUTORS file at the project root for a list of contributors.
//
///
/// A Protocol for named objects
///
public protocol Nameable {
/// The `name`
var name : String { get }
}
///
/// An `AsNameable` is a `Nameable` for an arbitrary typed `Item`
///
public struct AsNameable<Item> : Nameable {
/// The `name`
public var name : String
/// The `item`
public var item : Item
/// Initialize an insntance
///
/// - parameter name: the name
/// - parameter item: the item
///
public init (item: Item, name: String) {
self.name = name
self.item = item
}
}
///
/// A concreate Nameable class
///
open class Named : Nameable {
/// The `name`
public let name : String
/// Initialize an instance
///
/// - parameter name: The name
///
public init (name: String) {
self.name = name
}
}
///
/// A Namespace maintains a set of Named objects
///
public class Namespace<Object : Nameable> : Named {
/// The optional parent namespace
let parent : Namespace<Object>?
/// The separator
let separator = "."
/// The mapping from Name -> Value
var dictionary = Dictionary<String,Object>()
func hasObjectByName (_ obj: Object) -> Bool {
return nil != dictionary[obj.name]
}
/// Remove `obj` from `self` - based on `obj.name`
func remObjectByName (_ obj: Object) {
dictionary.removeValue (forKey: obj.name)
}
/// Add `obj` to `self` - overwritting any other object with `obj.name`
func addObjectByName (_ obj: Object) {
dictionary[obj.name] = obj
}
/// If one exists, return the object in `self` with `name`
func getObjectByName (_ name: String) -> Object? {
return dictionary[name]
}
///
/// The fullname of `obj` in namespace. Note the `obj` need not be in namespace.
///
/// - parameter obj:
///
/// - returns: The fullname
///
func fullname (_ obj: Nameable) -> String {
return (parent?.fullname(self) ?? name) + separator + obj.name
}
///
/// Create an instance
///
/// - parameter name: the name
/// - parameter parent: the parent namespace
///
public init (name: String, parent: Namespace<Object>) {
self.parent = parent
super.init(name: name)
}
///
/// Create an instance; the `parent` will be .None
///
/// - parameter name: The name
///
public override init (name: String) {
self.parent = nil
super.init(name: name)
}
}
| mit |
nathawes/swift | stdlib/public/Platform/Platform.swift | 6 | 12622 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import SwiftShims
import SwiftOverlayShims
#if os(Windows)
import ucrt
#endif
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
//===----------------------------------------------------------------------===//
// MacTypes.h
//===----------------------------------------------------------------------===//
public var noErr: OSStatus { return 0 }
/// The `Boolean` type declared in MacTypes.h and used throughout Core
/// Foundation.
///
/// The C type is a typedef for `unsigned char`.
@frozen
public struct DarwinBoolean : ExpressibleByBooleanLiteral {
@usableFromInline var _value: UInt8
@_transparent
public init(_ value: Bool) {
self._value = value ? 1 : 0
}
/// The value of `self`, expressed as a `Bool`.
@_transparent
public var boolValue: Bool {
return _value != 0
}
/// Create an instance initialized to `value`.
@_transparent
public init(booleanLiteral value: Bool) {
self.init(value)
}
}
extension DarwinBoolean : CustomReflectable {
/// Returns a mirror that reflects `self`.
public var customMirror: Mirror {
return Mirror(reflecting: boolValue)
}
}
extension DarwinBoolean : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return self.boolValue.description
}
}
extension DarwinBoolean : Equatable {
@_transparent
public static func ==(lhs: DarwinBoolean, rhs: DarwinBoolean) -> Bool {
return lhs.boolValue == rhs.boolValue
}
}
@_transparent
public // COMPILER_INTRINSIC
func _convertBoolToDarwinBoolean(_ x: Bool) -> DarwinBoolean {
return DarwinBoolean(x)
}
@_transparent
public // COMPILER_INTRINSIC
func _convertDarwinBooleanToBool(_ x: DarwinBoolean) -> Bool {
return x.boolValue
}
#endif
//===----------------------------------------------------------------------===//
// sys/errno.h
//===----------------------------------------------------------------------===//
public var errno : Int32 {
get {
return _swift_stdlib_getErrno()
}
set(val) {
return _swift_stdlib_setErrno(val)
}
}
//===----------------------------------------------------------------------===//
// stdio.h
//===----------------------------------------------------------------------===//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD) || os(PS4)
public var stdin : UnsafeMutablePointer<FILE> {
get {
return __stdinp
}
set {
__stdinp = newValue
}
}
public var stdout : UnsafeMutablePointer<FILE> {
get {
return __stdoutp
}
set {
__stdoutp = newValue
}
}
public var stderr : UnsafeMutablePointer<FILE> {
get {
return __stderrp
}
set {
__stderrp = newValue
}
}
public func dprintf(_ fd: Int, _ format: UnsafePointer<Int8>, _ args: CVarArg...) -> Int32 {
return withVaList(args) { va_args in
vdprintf(Int32(fd), format, va_args)
}
}
public func snprintf(ptr: UnsafeMutablePointer<Int8>, _ len: Int, _ format: UnsafePointer<Int8>, _ args: CVarArg...) -> Int32 {
return withVaList(args) { va_args in
return vsnprintf(ptr, len, format, va_args)
}
}
#elseif os(OpenBSD)
public var stdin: UnsafeMutablePointer<FILE> { return _swift_stdlib_stdin() }
public var stdout: UnsafeMutablePointer<FILE> { return _swift_stdlib_stdout() }
public var stderr: UnsafeMutablePointer<FILE> { return _swift_stdlib_stderr() }
#elseif os(Windows)
public var stdin: UnsafeMutablePointer<FILE> { return __acrt_iob_func(0) }
public var stdout: UnsafeMutablePointer<FILE> { return __acrt_iob_func(1) }
public var stderr: UnsafeMutablePointer<FILE> { return __acrt_iob_func(2) }
public var STDIN_FILENO: Int32 { return _fileno(stdin) }
public var STDOUT_FILENO: Int32 { return _fileno(stdout) }
public var STDERR_FILENO: Int32 { return _fileno(stderr) }
#endif
//===----------------------------------------------------------------------===//
// fcntl.h
//===----------------------------------------------------------------------===//
public func open(
_ path: UnsafePointer<CChar>,
_ oflag: Int32
) -> Int32 {
return _swift_stdlib_open(path, oflag, 0)
}
#if os(Windows)
public func open(
_ path: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: Int32
) -> Int32 {
return _swift_stdlib_open(path, oflag, mode)
}
#else
public func open(
_ path: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: mode_t
) -> Int32 {
return _swift_stdlib_open(path, oflag, mode)
}
public func openat(
_ fd: Int32,
_ path: UnsafePointer<CChar>,
_ oflag: Int32
) -> Int32 {
return _swift_stdlib_openat(fd, path, oflag, 0)
}
public func openat(
_ fd: Int32,
_ path: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: mode_t
) -> Int32 {
return _swift_stdlib_openat(fd, path, oflag, mode)
}
public func fcntl(
_ fd: Int32,
_ cmd: Int32
) -> Int32 {
return _swift_stdlib_fcntl(fd, cmd, 0)
}
public func fcntl(
_ fd: Int32,
_ cmd: Int32,
_ value: Int32
) -> Int32 {
return _swift_stdlib_fcntl(fd, cmd, value)
}
public func fcntl(
_ fd: Int32,
_ cmd: Int32,
_ ptr: UnsafeMutableRawPointer
) -> Int32 {
return _swift_stdlib_fcntlPtr(fd, cmd, ptr)
}
// !os(Windows)
#endif
#if os(Windows)
public var S_IFMT: Int32 { return Int32(0xf000) }
public var S_IFREG: Int32 { return Int32(0x8000) }
public var S_IFDIR: Int32 { return Int32(0x4000) }
public var S_IFCHR: Int32 { return Int32(0x2000) }
public var S_IFIFO: Int32 { return Int32(0x1000) }
public var S_IREAD: Int32 { return Int32(0x0100) }
public var S_IWRITE: Int32 { return Int32(0x0080) }
public var S_IEXEC: Int32 { return Int32(0x0040) }
#else
public var S_IFMT: mode_t { return mode_t(0o170000) }
public var S_IFIFO: mode_t { return mode_t(0o010000) }
public var S_IFCHR: mode_t { return mode_t(0o020000) }
public var S_IFDIR: mode_t { return mode_t(0o040000) }
public var S_IFBLK: mode_t { return mode_t(0o060000) }
public var S_IFREG: mode_t { return mode_t(0o100000) }
public var S_IFLNK: mode_t { return mode_t(0o120000) }
public var S_IFSOCK: mode_t { return mode_t(0o140000) }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
public var S_IFWHT: mode_t { return mode_t(0o160000) }
#endif
public var S_IRWXU: mode_t { return mode_t(0o000700) }
public var S_IRUSR: mode_t { return mode_t(0o000400) }
public var S_IWUSR: mode_t { return mode_t(0o000200) }
public var S_IXUSR: mode_t { return mode_t(0o000100) }
public var S_IRWXG: mode_t { return mode_t(0o000070) }
public var S_IRGRP: mode_t { return mode_t(0o000040) }
public var S_IWGRP: mode_t { return mode_t(0o000020) }
public var S_IXGRP: mode_t { return mode_t(0o000010) }
public var S_IRWXO: mode_t { return mode_t(0o000007) }
public var S_IROTH: mode_t { return mode_t(0o000004) }
public var S_IWOTH: mode_t { return mode_t(0o000002) }
public var S_IXOTH: mode_t { return mode_t(0o000001) }
public var S_ISUID: mode_t { return mode_t(0o004000) }
public var S_ISGID: mode_t { return mode_t(0o002000) }
public var S_ISVTX: mode_t { return mode_t(0o001000) }
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
public var S_ISTXT: mode_t { return S_ISVTX }
public var S_IREAD: mode_t { return S_IRUSR }
public var S_IWRITE: mode_t { return S_IWUSR }
public var S_IEXEC: mode_t { return S_IXUSR }
#endif
#endif
//===----------------------------------------------------------------------===//
// ioctl.h
//===----------------------------------------------------------------------===//
#if !os(Windows)
public func ioctl(
_ fd: CInt,
_ request: UInt,
_ value: CInt
) -> CInt {
return _swift_stdlib_ioctl(fd, request, value)
}
public func ioctl(
_ fd: CInt,
_ request: UInt,
_ ptr: UnsafeMutableRawPointer
) -> CInt {
return _swift_stdlib_ioctlPtr(fd, request, ptr)
}
public func ioctl(
_ fd: CInt,
_ request: UInt
) -> CInt {
return _swift_stdlib_ioctl(fd, request, 0)
}
// !os(Windows)
#endif
//===----------------------------------------------------------------------===//
// unistd.h
//===----------------------------------------------------------------------===//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
@available(*, unavailable, message: "Please use threads or posix_spawn*()")
public func fork() -> Int32 {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "Please use threads or posix_spawn*()")
public func vfork() -> Int32 {
fatalError("unavailable function can't be called")
}
#endif
//===----------------------------------------------------------------------===//
// signal.h
//===----------------------------------------------------------------------===//
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
public var SIG_DFL: sig_t? { return nil }
public var SIG_IGN: sig_t { return unsafeBitCast(1, to: sig_t.self) }
public var SIG_ERR: sig_t { return unsafeBitCast(-1, to: sig_t.self) }
public var SIG_HOLD: sig_t { return unsafeBitCast(5, to: sig_t.self) }
#elseif os(OpenBSD)
public var SIG_DFL: sig_t? { return nil }
public var SIG_IGN: sig_t { return unsafeBitCast(1, to: sig_t.self) }
public var SIG_ERR: sig_t { return unsafeBitCast(-1, to: sig_t.self) }
public var SIG_HOLD: sig_t { return unsafeBitCast(3, to: sig_t.self) }
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Haiku)
public typealias sighandler_t = __sighandler_t
public var SIG_DFL: sighandler_t? { return nil }
public var SIG_IGN: sighandler_t {
return unsafeBitCast(1, to: sighandler_t.self)
}
public var SIG_ERR: sighandler_t {
return unsafeBitCast(-1, to: sighandler_t.self)
}
public var SIG_HOLD: sighandler_t {
return unsafeBitCast(2, to: sighandler_t.self)
}
#elseif os(Cygwin)
public typealias sighandler_t = _sig_func_ptr
public var SIG_DFL: sighandler_t? { return nil }
public var SIG_IGN: sighandler_t {
return unsafeBitCast(1, to: sighandler_t.self)
}
public var SIG_ERR: sighandler_t {
return unsafeBitCast(-1, to: sighandler_t.self)
}
public var SIG_HOLD: sighandler_t {
return unsafeBitCast(2, to: sighandler_t.self)
}
#elseif os(Windows)
public var SIG_DFL: _crt_signal_t? { return nil }
public var SIG_IGN: _crt_signal_t {
return unsafeBitCast(1, to: _crt_signal_t.self)
}
public var SIG_ERR: _crt_signal_t {
return unsafeBitCast(-1, to: _crt_signal_t.self)
}
#elseif os(WASI)
// No signals support on WASI yet, see https://github.com/WebAssembly/WASI/issues/166.
#else
internal var _ignore = _UnsupportedPlatformError()
#endif
//===----------------------------------------------------------------------===//
// semaphore.h
//===----------------------------------------------------------------------===//
#if !os(Windows)
#if os(OpenBSD)
public typealias Semaphore = UnsafeMutablePointer<sem_t?>
#else
public typealias Semaphore = UnsafeMutablePointer<sem_t>
#endif
/// The value returned by `sem_open()` in the case of failure.
public var SEM_FAILED: Semaphore? {
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS)
// The value is ABI. Value verified to be correct for OS X, iOS, watchOS, tvOS.
return Semaphore(bitPattern: -1)
#elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku) || os(WASI)
// The value is ABI. Value verified to be correct on Glibc.
return Semaphore(bitPattern: 0)
#else
_UnsupportedPlatformError()
#endif
}
public func sem_open(
_ name: UnsafePointer<CChar>,
_ oflag: Int32
) -> Semaphore? {
return _stdlib_sem_open2(name, oflag)
}
public func sem_open(
_ name: UnsafePointer<CChar>,
_ oflag: Int32,
_ mode: mode_t,
_ value: CUnsignedInt
) -> Semaphore? {
return _stdlib_sem_open4(name, oflag, mode, value)
}
#endif
//===----------------------------------------------------------------------===//
// Misc.
//===----------------------------------------------------------------------===//
// Some platforms don't have `extern char** environ` imported from C.
#if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD) || os(OpenBSD) || os(PS4)
public var environ: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> {
return _swift_stdlib_getEnviron()
}
#elseif os(Linux)
public var environ: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> {
return __environ
}
#endif
| apache-2.0 |
nathawes/swift | test/Serialization/Inputs/def_clang_function_types.swift | 22 | 480 | import ctypes
public var has_fp_type: FunctionPointerReturningOpaqueTypedef?
public func use_inout<T>(arg: inout T) {}
@inlinable
public func use_fp_internally() {
// This currently bypasses the safety checks we do in export-checking
// because we don't check inlinable function bodies. It's plausible
// code, but more importantly it actually appears in the non-Darwin
// Foundation code.
var x: FunctionPointerReturningOpaqueTypedef2? = nil
use_inout(arg: &x)
}
| apache-2.0 |
Brightify/ReactantUI | Sources/Live/LiveUIError.swift | 1 | 282 | //
// LiveUIError.swift
// ReactantUI
//
// Created by Tadeas Kriz.
// Copyright © 2017 Brightify. All rights reserved.
//
import Foundation
public struct LiveUIError: Error {
let message: String
public init(message: String) {
self.message = message
}
}
| mit |
njdehoog/Spelt | SpeltTests/PostTests.swift | 1 | 415 | //
// PostTests.swift
// Spelt
//
// Created by Niels de Hoog on 30/08/16.
//
//
import XCTest
@testable import SpeltKit
class PostTests: XCTestCase {
func testThatItRequiresDate() {
XCTAssertThrowsError(try Post(path: "", contents: "", metadata: Metadata.none)) { error in
XCTAssertEqual(error as? Post.InitializationError, Post.InitializationError.missingDate)
}
}
}
| mit |
tomlokhorst/swift-json-gen | tests/Test13_struct_in_extension.swift | 1 | 279 | // Struct in extension: https://github.com/tomlokhorst/swift-json-gen/issues/22
// Doesn't appear to be possible to generate something for this?
struct Test13 {
let title: String
// let two: Test13.Test13b
}
extension Test13 {
struct Test13b {
let title: String
}
}
| mit |
svdo/ReRxSwift | Example/TableAndCollection/CollectionViewController.swift | 1 | 2483 | // Copyright © 2017 Stefan van den Oord. All rights reserved.
import UIKit
import ReSwift
import RxSwift
import RxDataSources
import ReRxSwift
private let mapStateToProps = { (appState: AppState) in
return CollectionViewController.Props(
categories: appState.tableAndCollection.categories
)
}
private let mapDispatchToActions = { (dispatch: @escaping DispatchFunction) in
return CollectionViewController.Actions(reverse: { dispatch(ReverseShops()) })
}
extension CollectionViewController: Connectable {
struct Props {
let categories: [ShopCategory]
}
struct Actions {
let reverse: () -> ()
}
}
class CollectionViewController: UICollectionViewController {
@IBOutlet var reverseButton: UIBarButtonItem!
let connection = Connection(store: store,
mapStateToProps: mapStateToProps,
mapDispatchToActions: mapDispatchToActions)
var dataSource: RxCollectionViewSectionedAnimatedDataSource<ShopCategory>!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.rightBarButtonItem = self.reverseButton
self.collectionView?.dataSource = nil
dataSource = RxCollectionViewSectionedAnimatedDataSource<ShopCategory>(configureCell: {
(dataSource, collectionView, indexPath, item) in
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NormalCell", for: indexPath)
(cell.viewWithTag(1) as? UILabel)?.text = item.name
(cell.viewWithTag(2) as? UILabel)?.text = String(item.rating)
return cell
}, configureSupplementaryView: {
(dataSource, collectionView, kind, indexPath) in
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: "HeaderView", for: indexPath)
(view.viewWithTag(1) as? UILabel)?.text = self.props.categories[indexPath.section].title
return view
})
self.connection.bind(\Props.categories, to: collectionView!.rx.items(dataSource: dataSource))
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
connection.connect()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
connection.disconnect()
}
@IBAction func reverseTapped(_ sender: UIBarButtonItem) {
actions.reverse()
}
}
| mit |
juyka/Rating-VolSU-iOS | Rating-VolSU-iOS/Rating-VolSU-iOS/CoreData/Group.swift | 1 | 415 | //
// Group.swift
// Rating-VolSU-iOS
//
// Created by Настя on 30.09.14.
// Copyright (c) 2014 VolSU. All rights reserved.
//
import Foundation
import CoreData
class Group: NSManagedObject {
@NSManaged var id: NSNumber
@NSManaged var name: String
@NSManaged var year: String
@NSManaged var faculty: Faculty
@NSManaged var students: NSSet
@NSManaged var favoritesItems: NSSet
}
| mit |
apple/swift-driver | Sources/SwiftDriver/IncrementalCompilation/ModuleDependencyGraphParts/Integrator.swift | 1 | 12110 | //===------------------ Integrator.swift ----------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
extension ModuleDependencyGraph {
// MARK: Integrator - state & creation
/// Integrates a \c SourceFileDependencyGraph into a \c ModuleDependencyGraph. See ``Integrator/integrate(from:dependencySource:into:)``
public struct Integrator {
// Shorthands
/*@_spi(Testing)*/ public typealias Graph = ModuleDependencyGraph
typealias DefinitionLocation = Graph.DefinitionLocation
public private(set) var invalidatedNodes = DirectlyInvalidatedNodeSet()
/// If integrating from an .swift file in the build, refers to the .swift file
/// Otherwise, refers to a .swiftmodule file
let dependencySource: DependencySource
/// the graph to be integrated
let sourceGraph: SourceFileDependencyGraph
/// the graph to be integrated into
let destination: ModuleDependencyGraph
/// Starts with all nodes in the `DependencySource` to be integrated.
/// Then as nodes are found in this source, they are removed from here.
/// After integration is complete, this dictionary contains the nodes that have disappeared from this `DependencySource`.
var disappearedNodes = [DependencyKey: Graph.Node]()
init(sourceGraph: SourceFileDependencyGraph,
dependencySource: DependencySource,
destination: ModuleDependencyGraph)
{
self.sourceGraph = sourceGraph
self.dependencySource = dependencySource
self.destination = destination
self.disappearedNodes = destination.nodeFinder
.findNodes(for: .known(dependencySource))
?? [:]
}
var reporter: IncrementalCompilationState.Reporter? {
destination.info.reporter
}
var sourceType: FileType {
dependencySource.typedFile.type
}
var isUpdating: Bool {
destination.phase.isUpdating
}
}
}
// MARK: - integrate a graph
extension ModuleDependencyGraph.Integrator {
/// Integrate a SourceFileDepGraph into the receiver.
///
/// Integration happens when the driver needs to read SourceFileDepGraph.
/// Common to scheduling both waves.
/// - Parameters:
/// - g: the graph to be integrated from
/// - dependencySource: holds the .swift or .swifmodule file containing the dependencies to be integrated that were read into `g`
/// - destination: the graph to be integrated into
/// - Returns: all nodes directly affected by the integration, plus nodes transitively affected by integrated external dependencies.
/// Because external dependencies may have transitive effects not captured by the frontend, changes from them are always transitively closed.
public static func integrate(
from g: SourceFileDependencyGraph,
dependencySource: DependencySource,
into destination: Graph
) -> DirectlyInvalidatedNodeSet {
precondition(g.internedStringTable === destination.internedStringTable)
var integrator = Self(sourceGraph: g,
dependencySource: dependencySource,
destination: destination)
integrator.integrate()
if destination.info.verifyDependencyGraphAfterEveryImport {
integrator.verifyAfterImporting()
}
destination.dotFileWriter?.write(g, for: dependencySource.typedFile,
internedStringTable: destination.internedStringTable)
destination.dotFileWriter?.write(destination)
return integrator.invalidatedNodes
}
private mutating func integrate() {
integrateEachSourceNode()
handleDisappearedNodes()
// Ensure transitive closure will get started.
destination.ensureGraphWillRetrace(invalidatedNodes)
}
private mutating func integrateEachSourceNode() {
sourceGraph.forEachNode { integrate(oneNode: $0) }
}
private mutating func handleDisappearedNodes() {
for (_, node) in disappearedNodes {
addDisappeared(node)
destination.nodeFinder.remove(node)
}
}
}
// MARK: - integrate one node
extension ModuleDependencyGraph.Integrator {
private mutating func integrate(
oneNode integrand: SourceFileDependencyGraph.Node)
{
guard integrand.definitionVsUse == .definition else {
// Uses are captured by recordWhatIsDependedUpon below.
return
}
let integratedNode = destination.nodeFinder.findNodes(for: integrand.key)
.flatMap {
integrateWithNodeDefinedHere( integrand, $0) ??
integrateWithNodeDefinedNowhere( integrand, $0)
}
?? integrateWithNewNode(integrand)
recordDefsForThisUse(integrand, integratedNode)
}
/// If a node to be integrated corresponds to one already in the destination graph for the same source, integrate it.
///
/// - Parameters:
/// - integrand: the node to be integrated
/// - nodesMatchingKey: all nodes in the destination graph with matching `DependencyKey`
/// - Returns: nil if a corresponding node did *not* already exist for the same source,
/// Otherwise, the integrated corresponding node.
/// If the integrated node was changed by the integration, it is added to ``invalidatedNodes``.
private mutating func integrateWithNodeDefinedHere(
_ integrand: SourceFileDependencyGraph.Node,
_ nodesMatchingKey: [DefinitionLocation: Graph.Node]
) -> Graph.Node? {
guard let matchHere = nodesMatchingKey[.known(dependencySource)] else {
return nil
}
assert(matchHere.definitionLocation == .known(dependencySource))
// Node was and still is. Do not remove it.
disappearedNodes.removeValue(forKey: matchHere.key)
enum FingerprintDisposition: String {
case missing, changed, stable
init(_ integrand: SourceFileDependencyGraph.Node,
_ matchHere: ModuleDependencyGraph.Node) {
switch (integrand.fingerprint, matchHere.fingerprint) {
case (nil, _):
self = .missing
case (_?, nil):
self = .changed
case let (integrandFingerprint?, matchHereFingerprint?):
self = integrandFingerprint == matchHereFingerprint
? .stable : .changed
}
}
}
let disposition = FingerprintDisposition(integrand, matchHere)
switch disposition {
case .stable:
break
case .missing:
// Since we only put fingerprints in enums, structs, classes, etc.,
// the driver really lacks the information to do much here.
// Just report it.
reporter?.report("Fingerprint \(disposition.rawValue) for existing \(matchHere.description(in: destination))")
break
case .changed:
matchHere.setFingerprint(integrand.fingerprint)
addChanged(matchHere)
reporter?.report("Fingerprint \(disposition.rawValue) for existing \(matchHere.description(in: destination))")
}
return matchHere
}
/// If a node to be integrated correspnds with a node in the graph belonging to no dependency source read as yet, integrate it.
/// The node to be integrated represents the definition of a declaration whose uses have already been seen.
/// The existing node is "moved" to its proper place in the graph, corresponding to the location of the definition of the declaration.
///
/// - Parameters:
/// - integrand: the node to be integrated
/// - nodesMatchingKey: all nodes in the destination graph with matching `DependencyKey`
/// - Returns: nil if a corresponding node *did* have a definition location, or the integrated corresponding node if it did not.
/// If the integrated node was changed by the integration, it is added to ``invalidatedNodes``.
private mutating func integrateWithNodeDefinedNowhere(
_ integrand: SourceFileDependencyGraph.Node,
_ nodesMatchingKey: [DefinitionLocation: Graph.Node]
) -> Graph.Node? {
guard let nodeWithNoDefinitionLocation = nodesMatchingKey[.unknown] else {
return nil
}
assert(nodesMatchingKey.count == 1,
"The graph never holds more than one node for a given key that has no definition location")
let integratedNode = destination.nodeFinder
.replace(nodeWithNoDefinitionLocation,
newDependencySource: self.dependencySource,
newFingerprint: integrand.fingerprint)
addPatriated(integratedNode)
return integratedNode
}
/// Integrate a node that correspnds with no known node.
///
/// - Parameters:
/// - integrand: the node to be integrated
/// - Returns: the integrated node
/// Since the integrated nodeis a change, it is added to ``invalidatedNodes``.
private mutating func integrateWithNewNode(
_ integrand: SourceFileDependencyGraph.Node
) -> Graph.Node {
precondition(integrand.definitionVsUse == .definition,
"Dependencies are arcs in the module graph")
let newNode = Graph.Node(
key: integrand.key,
fingerprint: integrand.fingerprint,
definitionLocation: .known(dependencySource))
let oldNode = destination.nodeFinder.insert(newNode)
assert(oldNode == nil, "Should be new!")
addNew(newNode)
return newNode
}
/// Find the keys of nodes used by this node, and record the def-use links.
/// Also see if any of those keys are external dependencies, and if such is a new dependency,
/// record the external dependency, and record the node as changed.
private mutating func recordDefsForThisUse(
_ sourceFileUseNode: SourceFileDependencyGraph.Node,
_ moduleUseNode: Graph.Node
) {
sourceGraph.forEachDefDependedUpon(by: sourceFileUseNode) { def in
let isNewUse = destination.nodeFinder.record(def: def.key,
use: moduleUseNode)
guard
isNewUse,
let externalDependency = def.key.designator.externalDependency
else {
return
}
recordInvalidations(
from: FingerprintedExternalDependency(externalDependency, def.fingerprint))
}
}
// A `moduleGraphUseNode` is used by an externalDependency key being integrated.
// Remember the dependency for later processing in externalDependencies, and
// also return it in results.
// Also the use node has changed.
private mutating func recordInvalidations(
from externalDependency: FingerprintedExternalDependency
) {
let integrand = ModuleDependencyGraph.ExternalIntegrand(externalDependency, in: destination)
let invalidated = destination.findNodesInvalidated(by: integrand)
recordUsesOfSomeExternal(invalidated)
}
}
// MARK: - Results {
extension ModuleDependencyGraph.Integrator {
/*@_spi(Testing)*/
mutating func recordUsesOfSomeExternal(_ invalidated: DirectlyInvalidatedNodeSet)
{
invalidatedNodes.formUnion(invalidated)
}
mutating func addDisappeared(_ node: Graph.Node) {
assert(isUpdating)
invalidatedNodes.insert(node)
}
mutating func addChanged(_ node: Graph.Node) {
assert(isUpdating)
invalidatedNodes.insert(node)
}
mutating func addPatriated(_ node: Graph.Node) {
if isUpdating {
reporter?.report("Discovered a definition for \(node.description(in: destination))")
invalidatedNodes.insert(node)
}
}
mutating func addNew(_ node: Graph.Node) {
if isUpdating {
reporter?.report("New definition: \(node.description(in: destination))")
invalidatedNodes.insert(node)
}
}
}
// MARK: - verification
extension ModuleDependencyGraph.Integrator {
@discardableResult
func verifyAfterImporting() -> Bool {
guard let nodesInFile = destination.nodeFinder.findNodes(for: .known(dependencySource)),
!nodesInFile.isEmpty
else {
fatalError("Just imported \(dependencySource), should have nodes")
}
return destination.verifyGraph()
}
}
| apache-2.0 |
practicalswift/swift | test/IRGen/Inputs/OtherModule.swift | 39 | 407 | import resilient_struct
public struct First {}
public struct Second {
public let resilientData: Size
}
private enum PrivateEnum {
case first(First?)
case second(Second?)
}
public struct Foo {
private var _property = PrivateEnum.first(nil)
}
internal enum InternalEnum {
case first(First?)
case second(Second?)
}
public struct Bar {
private var _property = InternalEnum.first(nil)
}
| apache-2.0 |
Alex-ZHOU/XYQSwift | XYQSwiftTests/Learn-from-Imooc/Play-with-Swift-2/02-Basics/02-Int.playground/Contents.swift | 1 | 683 | //
// 2-2 Swift 2.0基本类型之整型
// 02-Int.playground
//
// Created by AlexZHOU on 16/05/2017.
// Copyright © 2016年 AlexZHOU. All rights reserved.
//
import UIKit
var str = "02-Int"
print(str)
// 整型Int
var imInt:Int = 88
Int.max
Int.min
// UInt
UInt.max
UInt.min
// Int8
Int8.max
Int8.min
// 溢出在Swift语言中是一种编译错误
//let a: Int8 = 255
// UInt8
UInt8.max
UInt8.min
// Int16
Int16.max
Int16.min
// Int32
Int32.max
Int32.min
// Int64
Int64.max
Int64.min
// 二进制0b
let binaryInt: Int = 0b10001
// 八进制0o
let octalInt: Int = 0o21
// 十六进制0x
let hexInt:Int = 0x11
// 使用_标示数字位
let x = 1_000_000
| apache-2.0 |
carabina/Taylor | Taylor/Response.swift | 1 | 2986 | //
// response.swift
// TaylorTest
//
// Created by Jorge Izquierdo on 19/06/14.
// Copyright (c) 2014 Jorge Izquierdo. All rights reserved.
//
import Foundation
public class Response {
private var statusLine: String = ""
public var statusCode: Int = 200
public var headers: Dictionary<String, String> = Dictionary<String, String>()
public var body: NSData?
public var bodyString: String? {
didSet {
if headers["Content-Type"] == nil {
headers["Content-Type"] = FileTypes.get("txt")
}
}
}
var bodyData: NSData {
if let b = body {
return b
} else if bodyString != nil {
return NSData(data: bodyString!.dataUsingEncoding(NSUTF8StringEncoding)!)
}
return NSData()
}
private let http_protocol: String = "HTTP/1.1"
internal var codes = [
200: "OK",
201: "Created",
202: "Accepted",
300: "Multiple Choices",
301: "Moved Permanently",
302: "Found",
303: "See other",
400: "Bad TRequest",
401: "Unauthorized",
403: "Forbidden",
404: "Not Found",
500: "Internal Server Error",
502: "Bad Gateway",
503: "Service Unavailable"
]
public func redirect(url u: String) {
self.statusCode = 302
self.headers["Location"] = u
}
public func setFile(url: NSURL?) {
if let u = url, let data = NSData(contentsOfURL: u) {
self.body = data
self.headers["Content-Type"] = FileTypes.get(u.pathExtension ?? "")
} else {
self.setError(404)
}
}
public func setError(errorCode: Int){
self.statusCode = errorCode
if let a = self.codes[self.statusCode]{
self.bodyString = a
}
}
func headerData() -> NSData {
if let a = self.codes[self.statusCode]{
self.statusLine = a
}
if headers["Content-Length"] == nil{
headers["Content-Length"] = String(bodyData.length)
}
let startLine = "\(self.http_protocol) \(String(self.statusCode)) \(self.statusLine)\r\n"
var headersStr = ""
for (k, v) in self.headers {
headersStr += "\(k): \(v)\r\n"
}
headersStr += "\r\n"
let finalStr = String(format: startLine+headersStr)
return NSMutableData(data: finalStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!)
}
internal func generateResponse(method: HTTPMethod) -> NSData {
let headerData = self.headerData()
guard method != .HEAD else { return headerData }
return headerData + self.bodyData
}
} | mit |
pdcgomes/RendezVous | Vendor/docopt/Pattern.swift | 1 | 3978 | //
// Pattern.swift
// docopt
//
// Created by Pavel S. Mazurin on 3/1/15.
// Copyright (c) 2015 kovpas. All rights reserved.
//
import Foundation
typealias MatchResult = (match: Bool, left: [Pattern], collected: [Pattern])
internal class Pattern: Equatable, Hashable, CustomStringConvertible {
func fix() -> Pattern {
fixIdentities()
fixRepeatingArguments()
return self
}
var description: String {
get {
return "Pattern"
}
}
var hashValue: Int { get {
return self.description.hashValue
}
}
func fixIdentities(unq: [LeafPattern]? = nil) {}
func fixRepeatingArguments() -> Pattern {
let either = Pattern.transform(self).children.map { ($0 as! Required).children }
for c in either {
for ch in c {
let filteredChildren = c.filter {$0 == ch}
if filteredChildren.count > 1 {
for child in filteredChildren {
let e = child as! LeafPattern
if ((e is Argument) && !(e is Command)) || ((e is Option) && (e as! Option).argCount != 0) {
if e.value == nil {
e.value = [String]()
} else if !(e.value is [String]) {
e.value = e.value!.description.split()
}
}
if (e is Command) || ((e is Option) && (e as! Option).argCount == 0) {
e.value = 0
e.valueType = .Int
}
}
}
}
}
return self
}
static func isInParents(child: Pattern) -> Bool {
return (child as? Required != nil)
|| (child as? Optional != nil)
|| (child as? OptionsShortcut != nil)
|| (child as? Either != nil)
|| (child as? OneOrMore != nil)
}
static func transform(pattern: Pattern) -> Either {
var result = [[Pattern]]()
var groups = [[pattern]]
while !groups.isEmpty {
var children = groups.removeAtIndex(0)
let child: BranchPattern? = children.filter({ self.isInParents($0) }).first as? BranchPattern
if let child = child {
let index = children.indexOf(child)!
children.removeAtIndex(index)
if child is Either {
for pattern in child.children {
groups.append([pattern] + children)
}
} else if child is OneOrMore {
groups.append(child.children + child.children + children)
} else {
groups.append(child.children + children)
}
} else {
result.append(children)
}
}
return Either(result.map {Required($0)})
}
func flat() -> [LeafPattern] {
return flat(LeafPattern)
}
func flat<T: Pattern>(_: T.Type) -> [T] { // abstract
return []
}
func match<T: Pattern>(left: T, collected clld: [T]? = nil) -> MatchResult {
return match([left], collected: clld)
}
func match<T: Pattern>(left: [T], collected clld: [T]? = nil) -> MatchResult { // abstract
return (false, [], [])
}
func singleMatch<T: Pattern>(left: [T]) -> SingleMatchResult {return (0, nil)} // abstract
}
func ==(lhs: Pattern, rhs: Pattern) -> Bool {
if let lval = lhs as? BranchPattern, let rval = rhs as? BranchPattern {
return lval == rval
} else if let lval = lhs as? LeafPattern, let rval = rhs as? LeafPattern {
return lval == rval
}
return lhs === rhs // Pattern is "abstract" and shouldn't be instantiated :)
}
| mit |
dawsonbotsford/MobileAppsFall2015 | iOS/favorites/favorites/ViewController.swift | 1 | 692 | //
// ViewController.swift
// favorites
//
// Dawson Botsford
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var bookLabel: UILabel!
@IBOutlet weak var authorLabel: UILabel!
var user=Name()
@IBAction func unwindSegue (segue:UIStoryboardSegue){
bookLabel.text=user.firstName
authorLabel.text=user.lastName
}
override func viewDidLoad() {
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.
}
}
| mit |
admkopec/BetaOS | Kernel/Swift Extensions/Frameworks/Addressing/Addressing/Addressing.swift | 1 | 10736 | //
// Address.swift
// Addressing
//
// Created by Adam Kopeć on 11/5/17.
// Copyright © 2017-2018 Adam Kopeć. All rights reserved.
//
import Darwin.os
fileprivate func mapAddress(start: UInt, size: UInt) -> UInt {
guard start != 0 else {
return 0
}
let addr = UInt(io_map(UInt64(start & ~3), UInt((size + vm_page_mask) & ~vm_page_mask), (0x2 | 0x4 | 0x1)))
let newStart = UInt(kvtophys(UInt64(addr)))
if newStart != start && !isAHCI {
return addr + (start - newStart)
}
return addr
}
public final class Address: Numeric, Comparable, BinaryInteger {
public static let isSigned: Bool = false
public var hashValue: Int
public var magnitude: UInt
public var words: UInt.Words
public var bitWidth: Int
public var trailingZeroBitCount: Int
public typealias Magnitude = UInt
public typealias IntegerLiteralType = UInt
public typealias Words = UInt.Words
fileprivate var rawValue: UInt
fileprivate var rawValueVirt: UInt
fileprivate var sizeTomap: vm_size_t = vm_page_size
public var description: String {
return "Physical Address is 0x\(String(physical, radix: 16)), Virtual Address is 0x\(String(virtual, radix: 16))"
}
/**
Virtual address represented as a bit pattern.
*/
public var virtual: UInt {
if rawValueVirt >= 0x0fffff8000000000 {
return rawValueVirt
} else {
guard baseAddr != (0x0, 0x0) else {
rawValueVirt = mapAddress(start: physical, size: sizeTomap)
baseAddr = (physical, rawValueVirt)
return rawValueVirt
}
guard Int(max(physical, baseAddr.original)) - Int(min(physical, baseAddr.original)) < Int(vm_page_size) else {
rawValueVirt = mapAddress(start: physical, size: vm_page_size)
baseAddr = (physical, rawValueVirt)
return rawValueVirt
}
guard Int(Int(physical) - Int(baseAddr.original)) > Int(0) else {
rawValueVirt = mapAddress(start: physical, size: sizeTomap)
baseAddr = (physical, rawValueVirt)
return rawValueVirt
}
guard UInt64((UInt64(physical) + UInt64(baseAddr.mapped) - UInt64(baseAddr.original))) > UInt64(0) else {
rawValueVirt = mapAddress(start: physical, size: sizeTomap)
baseAddr = (physical, rawValueVirt)
return rawValueVirt
}
rawValueVirt = physical - baseAddr.original + baseAddr.mapped
return rawValueVirt
}
}
/**
Physical address represented as a bit pattern.
*/
public var physical: UInt {
if rawValue < 0x0fffff8000000000 {
return rawValue
} else {
return UInt(kvtophys(UInt64(rawValue)))
}
}
/**
Represents last mapped physical to virtual address pair
*/
fileprivate(set) public var baseAddr: (original: UInt, mapped: UInt) = (0x0, 0x0)
public static func ==(lhs: Address, rhs: Address) -> Bool {
return lhs.rawValue == rhs.rawValue
}
public static func ==(lhs: Address, rhs: UInt) -> Bool {
return lhs.rawValue == rhs
}
public static func ==(lhs: UInt, rhs: Address) -> Bool {
return lhs == rhs.rawValue
}
public static func <(lhs: Address, rhs: Address) -> Bool {
return lhs.rawValue < rhs.rawValue
}
public static func *(lhs: Address, rhs: Address) -> Address {
return Address(lhs.rawValue * rhs.rawValue)
}
public static func *=(lhs: inout Address, rhs: Address) {
lhs.rawValue *= rhs.rawValue
lhs.magnitude = lhs.rawValue
}
public static func +(lhs: Address, rhs: Address) -> Address {
return Address(lhs.rawValue + rhs.rawValue)
}
public static func +=(lhs: inout Address, rhs: Address) {
lhs.rawValue += rhs.rawValue
lhs.magnitude = lhs.rawValue
}
public static func -(lhs: Address, rhs: Address) -> Address {
return Address(lhs.rawValue - rhs.rawValue)
}
public static func -=(lhs: inout Address, rhs: Address) {
lhs.rawValue -= rhs.rawValue
lhs.magnitude = lhs.rawValue
}
public static func /(lhs: Address, rhs: Address) -> Address {
return Address(lhs.rawValue / rhs.rawValue)
}
public static func /=(lhs: inout Address, rhs: Address) {
lhs.rawValue /= rhs.rawValue
lhs.magnitude = lhs.rawValue
}
public static func %(lhs: Address, rhs: Address) -> Address {
return Address(lhs.rawValue % rhs.rawValue)
}
public static func %=(lhs: inout Address, rhs: Address) {
lhs.rawValue %= rhs.rawValue
lhs.magnitude = lhs.rawValue
}
public static func &=(lhs: inout Address, rhs: Address) {
lhs.rawValue &= rhs.rawValue
lhs.magnitude = lhs.rawValue
}
public static func |=(lhs: inout Address, rhs: Address) {
lhs.rawValue |= rhs.rawValue
lhs.magnitude = lhs.rawValue
}
public static func ^=(lhs: inout Address, rhs: Address) {
lhs.rawValue ^= rhs.rawValue
lhs.magnitude = lhs.rawValue
}
public static prefix func ~(x: Address) -> Address {
return Address(~x.rawValue)
}
public static func >>=<RHS>(lhs: inout Address, rhs: RHS) where RHS : BinaryInteger {
lhs.rawValue >>= rhs
lhs.magnitude = lhs.rawValue
}
public static func <<=<RHS>(lhs: inout Address, rhs: RHS) where RHS : BinaryInteger {
lhs.rawValue <<= rhs
lhs.magnitude = lhs.rawValue
}
public init(_ address: UInt, size: vm_size_t = vm_page_size, baseAddress: (UInt, UInt) = (0x0, 0x0)) {
rawValue = address
rawValueVirt = address
sizeTomap = size
if sizeTomap < vm_page_size {
sizeTomap = vm_page_size
}
baseAddr = baseAddress
magnitude = rawValue
hashValue = rawValue.hashValue
words = rawValue.words
bitWidth = rawValue.bitWidth
trailingZeroBitCount = rawValue.trailingZeroBitCount
}
public init(_ address64: UInt64, size: vm_size_t = vm_page_size, baseAddress: (UInt, UInt) = (0x0, 0x0)) {
rawValue = UInt(address64)
rawValueVirt = rawValue
sizeTomap = size
if sizeTomap < vm_page_size {
sizeTomap = vm_page_size
}
baseAddr = baseAddress
magnitude = rawValue
hashValue = rawValue.hashValue
words = rawValue.words
bitWidth = rawValue.bitWidth
trailingZeroBitCount = rawValue.trailingZeroBitCount
}
public init(_ address32: UInt32, size: vm_size_t = vm_page_size, baseAddress: (UInt, UInt) = (0x0, 0x0)) {
rawValue = UInt(address32)
rawValueVirt = UInt(address32)
sizeTomap = size
if sizeTomap < vm_page_size {
sizeTomap = vm_page_size
}
baseAddr = baseAddress
magnitude = rawValue
hashValue = rawValue.hashValue
words = rawValue.words
bitWidth = rawValue.bitWidth
trailingZeroBitCount = rawValue.trailingZeroBitCount
}
public init(integerLiteral value: UInt) {
rawValue = value
rawValueVirt = value
magnitude = rawValue
hashValue = rawValue.hashValue
words = rawValue.words
bitWidth = rawValue.bitWidth
trailingZeroBitCount = rawValue.trailingZeroBitCount
}
public init?<T>(exactly source: T) where T : BinaryInteger {
if let value = UInt(exactly: source) {
rawValue = value
rawValueVirt = value
magnitude = rawValue
hashValue = rawValue.hashValue
words = rawValue.words
bitWidth = rawValue.bitWidth
trailingZeroBitCount = rawValue.trailingZeroBitCount
} else {
return nil
}
}
public init?<T>(exactly source: T) where T : BinaryFloatingPoint{
if let value = UInt(exactly: source) {
rawValue = value
rawValueVirt = value
magnitude = rawValue
hashValue = rawValue.hashValue
words = rawValue.words
bitWidth = rawValue.bitWidth
trailingZeroBitCount = rawValue.trailingZeroBitCount
} else {
return nil
}
}
public init<T>(_ source: T) where T : BinaryInteger {
rawValue = UInt(source)
rawValueVirt = UInt(source)
magnitude = rawValue
hashValue = rawValue.hashValue
words = rawValue.words
bitWidth = rawValue.bitWidth
trailingZeroBitCount = rawValue.trailingZeroBitCount
}
public init<T>(truncatingIfNeeded source: T) where T : BinaryInteger {
rawValue = UInt(truncatingIfNeeded: source)
rawValueVirt = UInt(truncatingIfNeeded: source)
magnitude = rawValue
hashValue = rawValue.hashValue
words = rawValue.words
bitWidth = rawValue.bitWidth
trailingZeroBitCount = rawValue.trailingZeroBitCount
}
public init<T>(_ source: T) where T : BinaryFloatingPoint {
rawValue = UInt(source)
rawValueVirt = UInt(source)
magnitude = rawValue
hashValue = rawValue.hashValue
words = rawValue.words
bitWidth = rawValue.bitWidth
trailingZeroBitCount = rawValue.trailingZeroBitCount
}
public init<T>(clamping source: T) where T : BinaryInteger {
rawValue = UInt(clamping: source)
rawValueVirt = UInt(clamping: source)
magnitude = rawValue
hashValue = rawValue.hashValue
words = rawValue.words
bitWidth = rawValue.bitWidth
trailingZeroBitCount = rawValue.trailingZeroBitCount
}
}
| apache-2.0 |
dali-lab/DALI-Framework | Example/DALI/AppDelegate.swift | 1 | 2348 | //
// AppDelegate.swift
// DALI
//
// Created by johnlev on 08/09/2017.
// Copyright (c) 2017 johnlev. All rights reserved.
//
import UIKit
import DALI
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.]
DALIapi.configure(config: DALIConfig(serverURL: "http://10.0.1.33:3000", apiKey: "69222f5c9ea91af57b223e087bca601e7c151ef9c9848dcfbae4d08bb884", enableSockets: true))
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
zmian/xcore.swift | Sources/Xcore/Cocoa/Components/Currency/Money/Money.swift | 1 | 6759 | //
// Xcore
// Copyright © 2017 Xcore
// MIT license, see LICENSE file for details
//
import UIKit
/// A structure representing money type and set of attributes to formats the
/// output.
///
/// **Usage**
///
/// ```swift
/// let amount = Money(120.30)
/// .signed()
/// .font(.body)
/// .style(.removeMinorUnitIfZero)
///
/// // Display the amount in a label.
/// let amountLabel = UILabel()
/// amountLabel.setText(amount)
/// ```
///
/// **Using Custom Formats**
///
/// ```swift
/// let monthlyPayment = Money(9.99)
/// .font(.headline)
/// .attributedString(format: "%@ per month")
///
/// // Display the amount in a label.
/// let amountLabel = UILabel()
/// amountLabel.setText(amount)
/// ```
public struct Money: Equatable, Hashable, MutableAppliable {
/// The amount of money.
public var amount: Decimal
public init(_ amount: Decimal) {
self.amount = amount
shouldSuperscriptMinorUnit = Self.appearance().shouldSuperscriptMinorUnit
}
public init?(_ amount: Decimal?) {
guard let amount = amount else {
return nil
}
self.init(amount)
}
@_disfavoredOverload
public init?(_ amount: Double?) {
guard let amount = amount else {
return nil
}
self.init(amount)
}
/// The currency formatter used to format the amount.
///
/// The default value is `.shared`.
public var formatter: CurrencyFormatter = .shared
/// The limits of digits after the decimal separator.
public var fractionLength: ClosedRange<Int> = 2...2
/// The style used to format money components.
///
/// The default value is `.default`.
public var style: Components.Style = .default
/// The font used to display money components.
///
/// The default value is `.none`.
public var font: Components.Font = .none
/// The sign (+/-) used to format money components.
///
/// The default value is `.default`.
public var sign: Sign = .default
/// A property to indicate whether the color changes based on the amount.
public var color: Color = .none
/// The custom string to use when the amount is `0`.
///
/// This value is ignored if the `shouldDisplayZero` property is `true`.
///
/// The default value is `--`.
public var zeroString: String = "--"
/// A boolean property indicating whether `0` amount should be shown or
/// `zeroString` property value should be used instead.
///
/// The default value is `true`, meaning to display `0` amount.
public var shouldDisplayZero = true
/// A property to indicate whether the minor unit is rendered as superscript.
///
/// The default value is `false`.
public var shouldSuperscriptMinorUnit: Bool
/// A succinct label in a localized string that describes its contents
public var accessibilityLabel: String {
formatter.string(from: amount, fractionLength: fractionLength, style: style)
}
}
// MARK: - ExpressibleByFloatLiteral
extension Money: ExpressibleByFloatLiteral {
public init(floatLiteral value: FloatLiteralType) {
self.init(Decimal(value))
}
public init(_ value: Double) {
self.init(Decimal(value))
}
}
// MARK: - ExpressibleByIntegerLiteral
extension Money: ExpressibleByIntegerLiteral {
public init(integerLiteral value: IntegerLiteralType) {
self.init(Decimal(value))
}
public init(_ value: Int) {
self.init(Decimal(value))
}
}
// MARK: - CustomStringConvertible
extension Money: CustomStringConvertible {
public var description: String {
formatter.string(from: self, fractionLength: fractionLength)
}
}
// MARK: - StringRepresentable
extension Money: StringRepresentable {
public var stringSource: StringSourceType {
.attributedString(formatter.attributedString(from: self))
}
}
// MARK: - Appearance
extension Money {
/// This configuration exists to allow some of the properties to be configured
/// to match app's appearance style. The `UIAppearance` protocol doesn't work
/// when the stored properites are set using associated object.
///
/// **Usage**
///
/// ```swift
/// Money.appearance().shouldSuperscriptMinorUnit = true
/// ```
public final class Appearance: Appliable {
public var shouldSuperscriptMinorUnit = false
}
private static var appearanceProxy = Appearance()
public static func appearance() -> Appearance {
appearanceProxy
}
}
// MARK: - Chaining Syntactic Syntax
extension Money {
public func fractionLength(_ limit: Int) -> Self {
fractionLength(limit...limit)
}
public func fractionLength(_ limits: ClosedRange<Int>) -> Self {
applying {
$0.fractionLength = limits
}
}
public func style(_ style: Components.Style) -> Self {
applying {
$0.style = style
}
}
public func font(_ font: Components.Font) -> Self {
applying {
$0.font = font
}
}
public func sign(_ sign: Sign) -> Self {
applying {
$0.sign = sign
}
}
public func color(_ color: Color) -> Self {
applying {
$0.color = color
}
}
@_disfavoredOverload
public func color(_ color: UIColor) -> Self {
applying {
$0.color = .init(.init(color))
}
}
/// ```swift
/// // When the amount is positive then the output is "".
/// let amount = Money(120.30)
/// .sign(.default) // ← Specifying sign output
///
/// print(amount) // "$120.30"
///
/// // When the amount is negative then the output is "-".
/// let amount = Money(-120.30)
/// .sign(.default) // ← Specifying sign output
///
/// print(amount) // "-$120.30"
/// ```
public func signed() -> Self {
sign(.default)
}
/// Signed positive amount with (`"+"`), negative (`""`) and `0` amount omits
/// `+` or `-` sign.
public func onlyPositiveSigned() -> Self {
sign(.init(positive: amount == 0 ? "" : "+", negative: ""))
}
/// Zero amount will be displayed as "--".
///
/// - SeeAlso: `zeroString` to customize the default value.
public func dasherizeZero() -> Self {
applying {
$0.shouldDisplayZero = false
}
}
public func attributedString(format: String? = nil) -> NSAttributedString {
formatter.attributedString(from: self, format: format)
}
public func string(format: String? = nil) -> String {
formatter.string(from: self, fractionLength: fractionLength, format: format)
}
}
| mit |
Faifly/FFRealmUtils | FFRealmUtils/Classes/MarshalUtils.swift | 1 | 8983 | //
// MarshalUtils.swift
// FFRealmUtils
//
// Created by Artem Kalmykov on 10/17/17.
//
import Foundation
import Marshal
import RealmSwift
extension Dictionary: ValueType
{
public static func value(from object: Any) throws -> Dictionary
{
guard let dict = object as? Dictionary else
{
throw MarshalError.typeMismatch(expected: String.self, actual: type(of: object))
}
return dict
}
}
extension JSONParser
{
public static var dictionaryKey: String
{
return "_Marshal_DictionaryKey"
}
public static var dictionaryValue: String
{
return "_Marshal_DictionaryValue"
}
}
extension MarshaledObject
{
public func valueForDictionaryKey<T: ValueType>() throws -> T
{
return try self.value(for: JSONParser.dictionaryKey)
}
public func valueForDictionaryValue<T: ValueType>() throws -> T
{
return try self.value(for: JSONParser.dictionaryValue)
}
public func valueForDictionaryKey<T: ValueType>() throws -> [T]
{
return try self.value(for: JSONParser.dictionaryKey)
}
public func valueForDictionaryValue<T: ValueType>() throws -> [T]
{
return try self.value(for: JSONParser.dictionaryValue)
}
public func dictionaryTransformedValues<T: ValueType>(for key: KeyType) throws -> [T]
{
guard let castedSelf = self as? [AnyHashable : Any] else
{
return []
}
return try castedSelf.dictionaryTransformedValues(for: key)
}
public func transformDictionaryValues<T: ValueType>() throws -> [T]
{
guard let castedSelf = self as? [AnyHashable : Any] else
{
return []
}
return try castedSelf.transformDictionaryValues()
}
public func combinedDictionaryOfDictionariesOfArrays<T: ValueType>(for key: KeyType) throws -> [T]
{
guard let dictValue: [String : Any] = try self.value(for: key), dictValue is [String : [[String : Any]]] else
{
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: [AnyHashable : Any].self, actual: self.self)
}
var transformed: [[String : Any]] = []
for obj in (dictValue as! [String : [[String : Any]]])
{
for var subObj in obj.value
{
subObj[JSONParser.dictionaryKey] = obj.key
transformed.append(subObj)
}
}
return try transformed.map {
let value = try T.value(from: $0)
guard let element = value as? T else
{
throw MarshalError.typeMismatch(expected: T.self, actual: type(of: value))
}
return element
}
}
public func idMap<T: Object>(forKey key: KeyType) throws -> [T]
{
guard let ids = try self.any(for: key) as? [Any?] else
{
return []
}
return ids.flatMap({ id in
guard let objID = id else
{
return nil
}
return Realm.shared.object(ofType: T.self, forPrimaryKey: objID)
})
}
public func idMap<T: Object>(forKey key: KeyType) throws -> T?
{
let id: Any? = try self.any(for: key)
guard let objID = id else
{
return nil
}
return Realm.shared.object(ofType: T.self, forPrimaryKey: objID)
}
public func combinedDictionaryOfDictionariesOfArrays<T: ValueType>() throws -> [T]
{
guard let dictValue = self as? [String : Any], dictValue is [String : [[String : Any]]] else
{
throw MarshalError.typeMismatchWithKey(key: "self", expected: [AnyHashable : Any].self, actual: self.self)
}
var transformed: [[String : Any]] = []
for obj in (dictValue as! [String : [[String : Any]]])
{
for var subObj in obj.value
{
subObj[JSONParser.dictionaryKey] = obj.key
transformed.append(subObj)
}
}
return try transformed.map {
let value = try T.value(from: $0)
guard let element = value as? T else
{
throw MarshalError.typeMismatch(expected: T.self, actual: type(of: value))
}
return element
}
}
public func combinedDictionaryOfDictionaries<T: ValueType>() throws -> [T]
{
guard let dict = self as? [String : [String : Any]] else
{
throw MarshalError.typeMismatch(expected: [String : [String : Any]].self, actual: self.self)
}
var transformed: [[String : Any]] = []
for kv in dict
{
var subObj = kv.value
subObj[JSONParser.dictionaryKey] = kv.key
transformed.append(subObj)
}
return try transformed.map {
let value = try T.value(from: $0)
guard let element = value as? T else
{
throw MarshalError.typeMismatch(expected: T.self, actual: type(of: value))
}
return element
}
}
public func combinedDictionaryOfDictionaries<T: ValueType>(for key: KeyType) throws -> [T]
{
guard let dict: [String : Any] = try self.value(for: key), let dictValue = dict as? [String : [String : Any]] else
{
if self.optionalAny(for: key) != nil
{
throw MarshalError.typeMismatch(expected: [String : [String : Any]].self, actual: self.self)
}
else // If there is no such key, we shouldn't throw an error
{
return []
}
}
var transformed: [[String : Any]] = []
for kv in dictValue
{
var subObj = kv.value
subObj[JSONParser.dictionaryKey] = kv.key
transformed.append(subObj)
}
return try transformed.map {
let value = try T.value(from: $0)
guard let element = value as? T else
{
throw MarshalError.typeMismatch(expected: T.self, actual: type(of: value))
}
return element
}
}
}
extension Dictionary
{
public func dictionaryTransformedValues<T: ValueType>(for key: KeyType) throws -> [T]
{
guard let dictValue: [String : Any] = try self.value(for: key) else
{
if self.optionalAny(for: key) != nil
{
throw MarshalError.typeMismatchWithKey(key: key.stringValue, expected: [AnyHashable : Any].self, actual: self.self)
}
else // If there is no such key, we shouldn't throw an error
{
return []
}
}
return try dictValue.transformDictionaryValues()
}
public func transformDictionaryValues<T: ValueType>() throws -> [T]
{
let transformed = self.map({[JSONParser.dictionaryKey: $0, JSONParser.dictionaryValue: $1]})
return try transformed.map {
let value = try T.value(from: $0)
guard let element = value as? T else
{
throw MarshalError.typeMismatch(expected: T.self, actual: type(of: value))
}
return element
}
}
public func parseValue<T: ValueType>() throws -> T
{
let value = try T.value(from: self)
guard let obj = value as? T else
{
throw MarshalError.typeMismatch(expected: T.self, actual: type(of: value))
}
return obj
}
public func parseValue<T: ValueType>() throws -> T?
{
let value = try T.value(from: self)
guard let obj = value as? T else
{
return nil
}
return obj
}
}
extension Array
{
public func parseValues<T: ValueType>() throws -> [T]
{
return try self.map {
let value = try T.value(from: $0)
guard let element = value as? T else
{
throw MarshalError.typeMismatch(expected: T.self, actual: type(of: value))
}
return element
}
}
public func parseFlatValues<T: ValueType>() throws -> [T]
{
return try self.flatMap {
let value = try T.value(from: $0)
guard let element = value as? T else
{
return nil
}
return element
}
}
public func parseValues<T: ValueType>() throws -> [T?]
{
return try self.map {
let value = try T.value(from: $0)
guard let element = value as? T else
{
return nil
}
return element
}
}
}
| mit |
eofster/Telephone | Domain/SimpleSystemAudioDevice.swift | 1 | 1262 | //
// SimpleSystemAudioDevice.swift
// Telephone
//
// Copyright © 2008-2016 Alexey Kuznetsov
// Copyright © 2016-2021 64 Characters
//
// Telephone is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Telephone is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
public struct SimpleSystemAudioDevice: SystemAudioDevice {
public let identifier: Int
public let uniqueIdentifier: String
public let name: String
public let inputs: Int
public let outputs: Int
public let isBuiltIn: Bool
public let isNil: Bool = false
public init(identifier: Int, uniqueIdentifier: String, name: String, inputs: Int, outputs: Int, isBuiltIn: Bool) {
self.identifier = identifier
self.uniqueIdentifier = uniqueIdentifier
self.name = name
self.inputs = inputs
self.outputs = outputs
self.isBuiltIn = isBuiltIn
}
}
| gpl-3.0 |
alexshepard/Fishtacos | FishtacosUITests/FishtacosUITests.swift | 1 | 1066 | //
// FishtacosUITests.swift
// FishtacosUITests
//
// Created by Alex Shepard on 8/22/15.
// Copyright © 2015 Alex Shepard. All rights reserved.
//
import XCTest
class FishtacosUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
martinomamic/CarBooking | CarBooking/Controllers/BookingDetails/BookingDetailsPresenter.swift | 1 | 1110 | //
// BookingDetailsPresenter.swift
// CarBooking
//
// Created by Martino Mamic on 29/07/2017.
// Copyright © 2017 Martino Mamic. All rights reserved.
//
import Foundation
protocol BookingDetailsPresentationDelegate {
func presentBooking(response: BookingDetailsUseCases.FetchBooking.Response)
}
typealias DetailedBooking = BookingDetailsUseCases.FetchBooking.ViewModel.DetailedBooking
class BookingDetailsPresenter: BookingDetailsPresentationDelegate {
func presentBooking(response: BookingDetailsUseCases.FetchBooking.Response) {
let rb = response.booking
let displayedBooking = DetailedBooking(startDate: rb.startDate.bookingDate(),
endDate: rb.endDate.bookingDate(),
carInfo: rb.car.info, carName: rb.car.name, carImage: rb.car.image)
let viewModel = BookingDetailsUseCases.FetchBooking.ViewModel(detailedBooking: displayedBooking)
viewController?.displayBooking(viewModel: viewModel)
}
weak var viewController: BookingDetailsDisplayDelegate?
}
| mit |
objecthub/swift-numberkit | Tests/NumberKitTests/NumberUtilTests.swift | 1 | 1969 | //
// NumberUtilTests.swift
// NumberKit
//
// Created by Matthias Zenger on 12/08/2015.
// Copyright © 2015-2020 Matthias Zenger. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import XCTest
@testable import NumberKit
class NumberUtilTests: XCTestCase {
func testPow() {
XCTAssertEqual(1.toPower(of: 1), 1)
XCTAssertEqual(1.toPower(of: 9), 1)
XCTAssertEqual(7.toPower(of: 3), 7 * 7 * 7)
XCTAssertEqual(31.toPower(of: 7), 27512614111)
XCTAssertEqual((-5).toPower(of: 2), 25)
XCTAssertEqual((-5).toPower(of: 3), -125)
XCTAssertEqual((-5).toPower(of: 0), 1)
XCTAssertEqual(5.toPower(of: 0), 1)
}
func testPowOperator() {
XCTAssertEqual(1 ** 1, 1)
XCTAssertEqual(1 ** 9, 1)
XCTAssertEqual(7 ** 3, 7 * 7 * 7)
let many = 31 * 31 * 31 * 31
XCTAssertEqual((29 + 2) ** 7, many * 31 * 31 * 31)
XCTAssertEqual(-5 ** (1 + 1), 25)
XCTAssertEqual(-5 ** 3, -125)
XCTAssertEqual(-5 ** 0, 1)
XCTAssertEqual(5 ** 0, 1)
}
func testMinMax() {
XCTAssertEqual(min(0, 1), 0)
XCTAssertEqual(min(1, 0), 0)
XCTAssertEqual(min(-1, 0), -1)
XCTAssertEqual(min(0, -1), -1)
XCTAssertEqual(max(0, 1), 1)
XCTAssertEqual(max(1, 0), 1)
XCTAssertEqual(max(-1, 0), 0)
XCTAssertEqual(max(0, -1), 0)
}
static let allTests = [
("testPow", testPow),
("testPowOperator", testPowOperator),
("testMinMax", testMinMax),
]
}
| apache-2.0 |
ABTSoftware/SciChartiOSTutorial | v2.x/Sandbox/SciChart_Boilerplate_Swift_CustomLegend/CustomLegend/AppDelegate.swift | 1 | 2163 | //
// AppDelegate.swift
// CustomLegend
//
// Created by Gkol on 12/22/17.
// Copyright © 2017 Gkol. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
siejkowski/160 | onesixty/Source/TestingHelpers/TestFlowController.swift | 2 | 294 | import Foundation
import UIKit
@testable
import onesixty
class TestFlowController : FlowControllerProtocol {
var wasNavigationSetupReceived = false
func setupNavigationController(navigationController: UINavigationController) {
self.wasNavigationSetupReceived = true
}
}
| mit |
stripe/stripe-ios | Stripe/UIToolbar+Stripe_InputAccessory.swift | 1 | 1083 | //
// UIToolbar+Stripe_InputAccessory.swift
// StripeiOS
//
// Created by Jack Flintermann on 4/22/16.
// Copyright © 2016 Stripe, Inc. All rights reserved.
//
import UIKit
extension UIToolbar {
@objc(stp_inputAccessoryToolbarWithTarget:action:) class func stp_inputAccessoryToolbar(
withTarget target: Any?,
action: Selector
) -> Self {
let toolbar = self.init()
let flexibleItem = UIBarButtonItem(
barButtonSystemItem: .flexibleSpace,
target: nil,
action: nil
)
let nextItem = UIBarButtonItem(
title: STPLocalizedString("Next", "Button to move to the next text entry field"),
style: .done,
target: target,
action: action
)
toolbar.items = [flexibleItem, nextItem]
toolbar.autoresizingMask = .flexibleHeight
return toolbar
}
@objc(stp_setEnabled:) func stp_setEnabled(_ enabled: Bool) {
for barButtonItem in items ?? [] {
barButtonItem.isEnabled = enabled
}
}
}
| mit |
stripe/stripe-ios | StripePaymentsUI/StripePaymentsUI/Internal/UI/Views/Inputs/Card/STPCardExpiryInputTextField.swift | 1 | 1504 | //
// STPCardExpiryInputTextField.swift
// StripePaymentsUI
//
// Created by Cameron Sabol on 10/22/20.
// Copyright © 2020 Stripe, Inc. All rights reserved.
//
@_spi(STP) import StripeCore
import UIKit
class STPCardExpiryInputTextField: STPInputTextField {
public var expiryStrings: (month: String, year: String)? {
return (validator as! STPCardExpiryInputTextFieldValidator).expiryStrings
}
public convenience init(
prefillDetails: STPCardFormView.PrefillDetails? = nil
) {
self.init(
formatter: STPCardExpiryInputTextFieldFormatter(),
validator: STPCardExpiryInputTextFieldValidator()
)
self.text = prefillDetails?.formattedExpiry // pre-fill expiry if available
}
required init(
formatter: STPInputTextFieldFormatter,
validator: STPInputTextFieldValidator
) {
assert(formatter.isKind(of: STPCardExpiryInputTextFieldFormatter.self))
assert(validator.isKind(of: STPCardExpiryInputTextFieldValidator.self))
super.init(formatter: formatter, validator: validator)
keyboardType = .asciiCapableNumberPad
}
required init?(
coder: NSCoder
) {
super.init(coder: coder)
}
override func setupSubviews() {
super.setupSubviews()
accessibilityIdentifier = "expiration date"
placeholder = String.Localized.mm_yy
accessibilityLabel = String.Localized.expiration_date_accessibility_label
}
}
| mit |
austinzheng/swift-compiler-crashes | crashes-duplicates/20917-swift-constraints-constraintsystem-matchtypes.swift | 11 | 219 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
var d {
class A {
var d = 0 as a
let a = [ [Void{
| mit |
qblu/LiquidFloatingActionButton | Example/LiquidFloatingActionButton/ViewController.swift | 1 | 3743 | //
// ViewController.swift
// LiquidFloatingActionButton
//
// Created by Takuma Yoshida on 08/25/2015.
// Copyright (c) 2015 Takuma Yoshida. All rights reserved.
//
import UIKit
import SnapKit
import LiquidFloatingActionButton
public class CustomCell : LiquidFloatingCell {
var name: String = "sample"
init(icon: UIImage, name: String) {
self.name = name
super.init(icon: icon)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public override func setupView(view: UIView) {
super.setupView(view)
let label = UILabel()
label.text = name
label.textColor = UIColor.whiteColor()
label.font = UIFont(name: "Helvetica-Neue", size: 12)
addSubview(label)
label.snp_makeConstraints { make in
make.centerY.equalTo(self).offset(30)
make.width.equalTo(75)
make.centerX.height.equalTo(self)
}
}
}
class ViewController: UIViewController, LiquidFloatingActionButtonDataSource, LiquidFloatingActionButtonDelegate {
var cells: [LiquidFloatingCell] = []
var floatingActionButton: LiquidFloatingActionButton!
override func viewDidLoad() {
super.viewDidLoad()
// self.view.backgroundColor = UIColor(red: 55 / 255.0, green: 55 / 255.0, blue: 55 / 255.0, alpha: 1.0)
// Do any additional setup after loading the view, typically from a nib.
let createButton: (CGRect, LiquidFloatingActionButtonAnimateStyle) -> LiquidFloatingActionButton = { (frame, style) in
let floatingActionButton = LiquidFloatingActionButton(frame: frame)
floatingActionButton.animateStyle = style
floatingActionButton.dataSource = self
floatingActionButton.delegate = self
return floatingActionButton
}
let cellFactory: (String) -> LiquidFloatingCell = { (iconName) in
let cell = LiquidFloatingCell(icon: UIImage(named: iconName)!)
return cell
}
let customCellFactory: (String) -> LiquidFloatingCell = { (iconName) in
let cell = CustomCell(icon: UIImage(named: iconName)!, name: iconName)
return cell
}
cells.append(cellFactory("ic_cloud"))
cells.append(customCellFactory("ic_system"))
cells.append(cellFactory("ic_place"))
let floatingFrame = CGRect(x: self.view.frame.width - 56 - 16, y: self.view.frame.height - 56 - 16, width: 56, height: 56)
let bottomRightButton = createButton(floatingFrame, .Up)
let floatingFrame2 = CGRect(x: 16, y: 16, width: 56, height: 56)
let topLeftButton = createButton(floatingFrame2, .Down)
let floatingFrameBottomMiddle = CGRect(
x: (self.view.frame.width - 56 - 16) / 2,
y: self.view.frame.height - 56 - 16,
width: 56,
height: 56
)
let bottomMiddleButton = createButton(floatingFrameBottomMiddle, .FanUp)
self.view.addSubview(bottomRightButton)
self.view.addSubview(topLeftButton)
self.view.addSubview(bottomMiddleButton)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfCells(liquidFloatingActionButton: LiquidFloatingActionButton) -> Int {
return cells.count
}
func cellForIndex(index: Int) -> LiquidFloatingCell {
return cells[index]
}
func liquidFloatingActionButton(liquidFloatingActionButton: LiquidFloatingActionButton, didSelectItemAtIndex index: Int) {
print("did Tapped! \(index)")
liquidFloatingActionButton.close()
}
}
| mit |
anicolaspp/rate-my-meetings-ios | RateMyMeetings/Team.swift | 1 | 285 | //
// Team.swift
// RateMyMeetings
//
// Created by Nicolas Perez on 11/23/15.
// Copyright © 2015 Nicolas Perez. All rights reserved.
//
import Foundation
class Team {
let name: String?
var members: [User]?
init(name: String) {
self.name = name
}
} | mit |
austinzheng/swift-compiler-crashes | fixed/00128-swift-lexer-getlocforendoftoken.swift | 12 | 235 | // 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 c<e> {
let d: [( h
}
func b(g: f) -> <e>(()-> e) -> i
| mit |
eurofurence/ef-app_ios | Packages/EurofurenceModel/Sources/EurofurenceModel/Public/Objects/Credential.swift | 2 | 614 | import Foundation
public struct Credential {
public var username: String
public var registrationNumber: Int
public var authenticationToken: String
public var tokenExpiryDate: Date
public init(username: String, registrationNumber: Int, authenticationToken: String, tokenExpiryDate: Date) {
self.username = username
self.registrationNumber = registrationNumber
self.authenticationToken = authenticationToken
self.tokenExpiryDate = tokenExpiryDate
}
public func isValid(currentDate: Date) -> Bool {
return currentDate < tokenExpiryDate
}
}
| mit |
NghiaTranUIT/Titan | TitanCore/TitanCore/StatusBarViewModel.swift | 2 | 1600 | //
// StatusBarViewModel.swift
// TitanCore
//
// Created by Nghia Tran on 4/25/17.
// Copyright © 2017 nghiatran. All rights reserved.
//
import Foundation
import RxSwift
import SwiftyPostgreSQL
import RxCocoa
public protocol StatusBarViewModelType {
var input: StatusBarViewModelInput {get}
var output: StatusBarViewModelOutput {get}
}
public protocol StatusBarViewModelInput {
var queryResultPublisher: PublishSubject<QueryResult> {get}
}
public protocol StatusBarViewModelOutput {
var statusDriver: Driver<String>! {get}
}
//
// MARK: - StatusBarViewModel
open class StatusBarViewModel: BaseViewModel, StatusBarViewModelType, StatusBarViewModelInput, StatusBarViewModelOutput {
//
// MARK: - Type
public var input: StatusBarViewModelInput {return self}
public var output: StatusBarViewModelOutput {return self}
//
// MARK: - Input
public var queryResultPublisher = PublishSubject<QueryResult>()
//
// MARK: - Output
public var statusDriver: Driver<String>!
//
// MARK: - Init
override public init() {
super.init()
self.binding()
}
fileprivate func binding() {
// Update statu bar
self.statusDriver = self.queryResultPublisher.asObserver().map { (queryResult) -> String in
let count = queryResult.rowsAffected
if count <= 0 {
return "0 Rows"
}
return "Rows \(count)"
}
.asDriver(onErrorJustReturn: "0 Rows")
}
}
| mit |
back2mach/OAuthSwift | Sources/OAuth2Swift.swift | 1 | 15296 | //
// OAuth2Swift.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/22/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import Foundation
open class OAuth2Swift: OAuthSwift {
// If your oauth provider need to use basic authentification
// set value to true (default: false)
open var accessTokenBasicAuthentification = false
// Set to true to deactivate state check. Be careful of CSRF
open var allowMissingStateCheck: Bool = false
// Encode callback url. Default false
// issue #339, pr ##325
open var encodeCallbackURL: Bool = false
var consumerKey: String
var consumerSecret: String
var authorizeUrl: String
var accessTokenUrl: String?
var responseType: String
var contentType: String?
// MARK: init
public convenience init(consumerKey: String, consumerSecret: String, authorizeUrl: String, accessTokenUrl: String, responseType: String) {
self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, authorizeUrl: authorizeUrl, responseType: responseType)
self.accessTokenUrl = accessTokenUrl
}
public convenience init(consumerKey: String, consumerSecret: String, authorizeUrl: String, accessTokenUrl: String, responseType: String, contentType: String) {
self.init(consumerKey: consumerKey, consumerSecret: consumerSecret, authorizeUrl: authorizeUrl, responseType: responseType)
self.accessTokenUrl = accessTokenUrl
self.contentType = contentType
}
public init(consumerKey: String, consumerSecret: String, authorizeUrl: String, responseType: String) {
self.consumerKey = consumerKey
self.consumerSecret = consumerSecret
self.authorizeUrl = authorizeUrl
self.responseType = responseType
super.init(consumerKey: consumerKey, consumerSecret: consumerSecret)
self.client.credential.version = .oauth2
}
public convenience init?(parameters: ConfigParameters) {
guard let consumerKey = parameters["consumerKey"], let consumerSecret = parameters["consumerSecret"],
let responseType = parameters["responseType"], let authorizeUrl = parameters["authorizeUrl"] else {
return nil
}
if let accessTokenUrl = parameters["accessTokenUrl"] {
self.init(consumerKey:consumerKey, consumerSecret: consumerSecret,
authorizeUrl: authorizeUrl, accessTokenUrl: accessTokenUrl, responseType: responseType)
} else {
self.init(consumerKey:consumerKey, consumerSecret: consumerSecret,
authorizeUrl: authorizeUrl, responseType: responseType)
}
}
open var parameters: ConfigParameters {
return [
"consumerKey": consumerKey,
"consumerSecret": consumerSecret,
"authorizeUrl": authorizeUrl,
"accessTokenUrl": accessTokenUrl ?? "",
"responseType": responseType
]
}
// MARK: functions
@discardableResult
open func authorize(withCallbackURL callbackURL: URL, scope: String, state: String, parameters: Parameters = [:], headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? {
self.observeCallback { [weak self] url in
guard let this = self else { OAuthSwift.retainError(failure); return }
var responseParameters = [String: String]()
if let query = url.query {
responseParameters += query.parametersFromQueryString
}
if let fragment = url.fragment, !fragment.isEmpty {
responseParameters += fragment.parametersFromQueryString
}
if let accessToken = responseParameters["access_token"] {
this.client.credential.oauthToken = accessToken.safeStringByRemovingPercentEncoding
if let expiresIn: String = responseParameters["expires_in"], let offset = Double(expiresIn) {
this.client.credential.oauthTokenExpiresAt = Date(timeInterval: offset, since: Date())
}
success(this.client.credential, nil, responseParameters)
} else if let code = responseParameters["code"] {
if !this.allowMissingStateCheck {
guard let responseState = responseParameters["state"] else {
failure?(OAuthSwiftError.missingState)
return
}
if responseState != state {
failure?(OAuthSwiftError.stateNotEqual(state: state, responseState: responseState))
return
}
}
if let handle = this.postOAuthAccessTokenWithRequestToken(
byCode: code.safeStringByRemovingPercentEncoding,
callbackURL: callbackURL, headers: headers, success: success, failure: failure) {
this.putHandle(handle, withKey: UUID().uuidString)
}
} else if let error = responseParameters["error"] {
let description = responseParameters["error_description"] ?? ""
let message = NSLocalizedString(error, comment: description)
failure?(OAuthSwiftError.serverError(message: message))
} else {
let message = "No access_token, no code and no error provided by server"
failure?(OAuthSwiftError.serverError(message: message))
}
}
var queryString = "client_id=\(self.consumerKey)"
if encodeCallbackURL {
queryString += "&redirect_uri=\(callbackURL.absoluteString.urlEncodedString)"
} else {
queryString += "&redirect_uri=\(callbackURL.absoluteString)"
}
queryString += "&response_type=\(self.responseType)"
if !scope.isEmpty {
queryString += "&scope=\(scope)"
}
if !state.isEmpty {
queryString += "&state=\(state)"
}
for param in parameters {
queryString += "&\(param.0)=\(param.1)"
}
var urlString = self.authorizeUrl
urlString += (self.authorizeUrl.contains("?") ? "&" : "?")
if let encodedQuery = queryString.urlQueryEncoded, let queryURL = URL(string: urlString + encodedQuery) {
self.authorizeURLHandler.handle(queryURL)
return self
} else {
self.cancel() // ie. remove the observer.
failure?(OAuthSwiftError.encodingError(urlString: urlString))
return nil
}
}
@discardableResult
open func authorize(withCallbackURL urlString: String, scope: String, state: String, parameters: Parameters = [:], headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? {
guard let url = URL(string: urlString) else {
failure?(OAuthSwiftError.encodingError(urlString: urlString))
return nil
}
return authorize(withCallbackURL: url, scope: scope, state: state, parameters: parameters, headers: headers, success: success, failure: failure)
}
func postOAuthAccessTokenWithRequestToken(byCode code: String, callbackURL: URL, headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? {
var parameters = OAuthSwift.Parameters()
parameters["client_id"] = self.consumerKey
parameters["client_secret"] = self.consumerSecret
parameters["code"] = code
parameters["grant_type"] = "authorization_code"
parameters["redirect_uri"] = callbackURL.absoluteString.safeStringByRemovingPercentEncoding
return requestOAuthAccessToken(withParameters: parameters, headers: headers, success: success, failure: failure)
}
@discardableResult
open func renewAccessToken(withRefreshToken refreshToken: String, parameters: OAuthSwift.Parameters? = nil, headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? {
var parameters = parameters ?? OAuthSwift.Parameters()
parameters["client_id"] = self.consumerKey
parameters["client_secret"] = self.consumerSecret
parameters["refresh_token"] = refreshToken
parameters["grant_type"] = "refresh_token"
return requestOAuthAccessToken(withParameters: parameters, headers: headers, success: success, failure: failure)
}
fileprivate func requestOAuthAccessToken(withParameters parameters: OAuthSwift.Parameters, headers: OAuthSwift.Headers? = nil, success: @escaping TokenSuccessHandler, failure: FailureHandler?) -> OAuthSwiftRequestHandle? {
let successHandler: OAuthSwiftHTTPRequest.SuccessHandler = { [unowned self]
response in
let responseJSON: Any? = try? response.jsonObject(options: .mutableContainers)
let responseParameters: OAuthSwift.Parameters
if let jsonDico = responseJSON as? [String:Any] {
responseParameters = jsonDico
} else {
responseParameters = response.string?.parametersFromQueryString ?? [:]
}
guard let accessToken = responseParameters["access_token"] as? String else {
let message = NSLocalizedString("Could not get Access Token", comment: "Due to an error in the OAuth2 process, we couldn't get a valid token.")
failure?(OAuthSwiftError.serverError(message: message))
return
}
if let refreshToken = responseParameters["refresh_token"] as? String {
self.client.credential.oauthRefreshToken = refreshToken.safeStringByRemovingPercentEncoding
}
if let expiresIn = responseParameters["expires_in"] as? String, let offset = Double(expiresIn) {
self.client.credential.oauthTokenExpiresAt = Date(timeInterval: offset, since: Date())
} else if let expiresIn = responseParameters["expires_in"] as? Double {
self.client.credential.oauthTokenExpiresAt = Date(timeInterval: expiresIn, since: Date())
}
self.client.credential.oauthToken = accessToken.safeStringByRemovingPercentEncoding
success(self.client.credential, response, responseParameters)
}
guard let accessTokenUrl = accessTokenUrl else {
let message = NSLocalizedString("access token url not defined", comment: "access token url not defined with code type auth")
failure?(OAuthSwiftError.configurationError(message: message))
return nil
}
if self.contentType == "multipart/form-data" {
// Request new access token by disabling check on current token expiration. This is safe because the implementation wants the user to retrieve a new token.
return self.client.postMultiPartRequest(accessTokenUrl, method: .POST, parameters: parameters, headers: headers, checkTokenExpiration: false, success: successHandler, failure: failure)
} else {
// special headers
var finalHeaders: OAuthSwift.Headers? = nil
if accessTokenBasicAuthentification {
let authentification = "\(self.consumerKey):\(self.consumerSecret)".data(using: String.Encoding.utf8)
if let base64Encoded = authentification?.base64EncodedString(options: Data.Base64EncodingOptions(rawValue: 0)) {
finalHeaders += ["Authorization": "Basic \(base64Encoded)"] as OAuthSwift.Headers
}
}
// Request new access token by disabling check on current token expiration. This is safe because the implementation wants the user to retrieve a new token.
return self.client.request(accessTokenUrl, method: .POST, parameters: parameters, headers: finalHeaders, checkTokenExpiration: false, success: successHandler, failure: failure)
}
}
/**
Convenience method to start a request that must be authorized with the previously retrieved access token.
Since OAuth 2 requires support for the access token refresh mechanism, this method will take care to automatically
refresh the token if needed such that the developer only has to be concerned about the outcome of the request.
- parameter url: The url for the request.
- parameter method: The HTTP method to use.
- parameter parameters: The request's parameters.
- parameter headers: The request's headers.
- parameter onTokenRenewal: Optional callback triggered in case the access token renewal was required in order to properly authorize the request.
- parameter success: The success block. Takes the successfull response and data as parameter.
- parameter failure: The failure block. Takes the error as parameter.
*/
@discardableResult
open func startAuthorizedRequest(_ url: String, method: OAuthSwiftHTTPRequest.Method, parameters: OAuthSwift.Parameters, headers: OAuthSwift.Headers? = nil, onTokenRenewal: TokenRenewedHandler? = nil, success: @escaping OAuthSwiftHTTPRequest.SuccessHandler, failure: @escaping OAuthSwiftHTTPRequest.FailureHandler) -> OAuthSwiftRequestHandle? {
// build request
return self.client.request(url, method: method, parameters: parameters, headers: headers, success: success) { (error) in
switch error {
case OAuthSwiftError.tokenExpired:
let _ = self.renewAccessToken(withRefreshToken: self.client.credential.oauthRefreshToken, headers: headers, success: { (credential, _, _) in // Ommit response parameters so they don't override the original ones
// We have successfully renewed the access token.
// If provided, fire the onRenewal closure
if let renewalCallBack = onTokenRenewal {
renewalCallBack(credential)
}
// Reauthorize the request again, this time with a brand new access token ready to be used.
let _ = self.startAuthorizedRequest(url, method: method, parameters: parameters, headers: headers, onTokenRenewal: onTokenRenewal, success: success, failure: failure)
}, failure: failure)
default:
failure(error)
}
}
}
@discardableResult
open func authorize(deviceToken deviceCode: String, success: @escaping TokenRenewedHandler, failure: @escaping OAuthSwiftHTTPRequest.FailureHandler) -> OAuthSwiftRequestHandle? {
var parameters = OAuthSwift.Parameters()
parameters["client_id"] = self.consumerKey
parameters["client_secret"] = self.consumerSecret
parameters["code"] = deviceCode
parameters["grant_type"] = "http://oauth.net/grant_type/device/1.0"
return requestOAuthAccessToken(
withParameters: parameters,
success: { (credential, _, parameters) in
success(credential)
}, failure: failure
)
}
}
| mit |
ohadh123/MuscleUp- | MuscleUp!/CurlsGameScene.swift | 1 | 201 | //
// CurlsGameScene.swift
// MuscleUp!
//
// Created by Ohad Koronyo on 7/8/17.
// Copyright © 2017 Ohad Koronyo. All rights reserved.
//
import SpriteKit
class CurlsGameScene: SKScene{
}
| apache-2.0 |
CartoDB/mobile-ios-samples | AdvancedMap.Objective-C/AdvancedMap/ProgressLabel.swift | 1 | 1842 | //
// ProgressLabel.swift
// AdvancedMap.Swift
//
// Created by Aare Undo on 26/06/2017.
// Copyright © 2017 CARTO. All rights reserved.
//
import Foundation
import UIKit
@objc class ProgressLabel : AlertBaseView {
@objc var label: UILabel!
@objc var progressBar: UIView!
var height: CGFloat!
convenience init() {
self.init(frame: CGRect.zero)
backgroundColor = Colors.transparentGray
label = UILabel()
label.textColor = UIColor.white
label.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
label.textAlignment = .center
addSubview(label)
progressBar = UIView()
progressBar.backgroundColor = Colors.appleBlue
addSubview(progressBar)
alpha = 0
}
override func layoutSubviews() {
label.frame = bounds
}
@objc func update(text: String, progress: CGFloat) {
if (!isVisible()) {
show()
}
update(text: text)
updateProgressBar(progress: progress)
}
@objc func update(text: String) {
label.text = text
}
@objc func complete(message: String) {
if (!isVisible()) {
show()
}
label.text = message
Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(onTimerCompleted), userInfo: nil, repeats: false)
}
@objc func onTimerCompleted() {
hide()
}
@objc func updateProgressBar(progress: CGFloat) {
let width: CGFloat = (frame.width * progress) / 100
let height: CGFloat = 3
let y: CGFloat = frame.height - height
progressBar.frame = CGRect(x: 0, y: y, width: width, height: height)
}
}
| bsd-2-clause |
liuCodeBoy/Ant | Ant/Ant/LunTan/Detials/Controller/CarServiceDVC.swift | 1 | 8539 | //
// CarServiceDVC.swift
// Ant
//
// Created by Weslie on 2017/8/4.
// Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import UIKit
class CarServiceDVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView?
var modelInfo: LunTanDetialModel?
override func viewDidLoad() {
super.viewDidLoad()
loadDetialTableView()
let view = Menu()
self.tabBarController?.tabBar.isHidden = true
view.frame = CGRect(x: 0, y: screenHeight - 124, width: screenWidth, height: 60)
self.view.addSubview(view)
}
func loadDetialTableView() {
let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 60)
self.tableView = UITableView(frame: frame, style: .grouped)
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.tableView?.backgroundColor = UIColor.init(white: 0.9, alpha: 1)
self.tableView?.separatorStyle = .singleLine
tableView?.register(UINib(nibName: "CarServiceBasicInfo", bundle: nil), forCellReuseIdentifier: "carServiceBasicInfo")
tableView?.register(UINib(nibName: "CarServiceDetial", bundle: nil), forCellReuseIdentifier: "carServiceDetial")
tableView?.register(UINib(nibName: "LocationInfo", bundle: nil), forCellReuseIdentifier: "locationInfo")
tableView?.register(UINib(nibName: "DetialControduction", bundle: nil), forCellReuseIdentifier: "detialControduction")
tableView?.register(UINib(nibName: "ConnactOptions", bundle: nil), forCellReuseIdentifier: "connactOptions")
tableView?.register(UINib(nibName: "MessageHeader", bundle: nil), forCellReuseIdentifier: "messageHeader")
tableView?.register(UINib(nibName: "MessagesCell", bundle: nil), forCellReuseIdentifier: "messagesCell")
tableView?.separatorStyle = .singleLine
self.view.addSubview(tableView!)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 5
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0: return 3
case 2: return 5
case 4: return 10
default: return 1
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
switch section {
case 0:
let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width * 0.6)
let urls = [
"http://img3.cache.netease.com/photo/0009/2016-05-27/BO1HVHOV0AI20009.jpg",
"http://img3.cache.netease.com/photo/0009/2016-05-27/BO1HVIJ30AI20009.png",
"http://img5.cache.netease.com/photo/0009/2016-05-27/BO1HVLIM0AI20009.jpg",
"http://img6.cache.netease.com/photo/0009/2016-05-27/BO1HVJCD0AI20009.jpg",
"http://img2.cache.netease.com/photo/0009/2016-05-27/BO1HVPUT0AI20009.png"
]
var urlArray: [URL] = [URL]()
for str in urls {
let url = URL(string: str)
urlArray.append(url!)
}
return LoopView(images: urlArray, frame: frame, isAutoScroll: true)
case 1:
let detialHeader = Bundle.main.loadNibNamed("DetialHeaderView", owner: nil, options: nil)?.first as? DetialHeaderView
detialHeader?.DetialHeaderLabel.text = "详情介绍"
return detialHeader
case 2:
let connactHeader = Bundle.main.loadNibNamed("DetialHeaderView", owner: nil, options: nil)?.first as? DetialHeaderView
connactHeader?.DetialHeaderLabel.text = "联系人方式"
return connactHeader
default:
return nil
}
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if section == 2 {
return Bundle.main.loadNibNamed("Share", owner: nil, options: nil)?.first as? UIView
} else {
return nil
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section {
case 0:
return UIScreen.main.bounds.width * 0.6
case 1:
return 30
case 2:
return 30
case 3:
return 10
case 4:
return 0.00001
default:
return 0.00001
}
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 2 {
return 140
} else {
return 0.00001
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell?
switch indexPath.section {
case 0:
switch indexPath.row {
case 0: cell = tableView.dequeueReusableCell(withIdentifier: "carServiceBasicInfo")
if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! {
cell?.separatorInset = UIEdgeInsets.zero
}
case 1: cell = tableView.dequeueReusableCell(withIdentifier: "carServiceDetial")
if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! {
cell?.separatorInset = UIEdgeInsets.zero
}
case 2: cell = tableView.dequeueReusableCell(withIdentifier: "locationInfo")
default: break
}
case 1: cell = tableView.dequeueReusableCell(withIdentifier: "detialControduction")
case 2:
let connactoptions = tableView.dequeueReusableCell(withIdentifier: "connactOptions") as! ConnactOptions
// guard modelInfo.con else {
// <#statements#>
// }
if let contact = modelInfo?.connactDict[indexPath.row] {
if let key = contact.first?.key{
connactoptions.con_Ways.text = key
}
}
if let value = modelInfo?.connactDict[indexPath.row].first?.value {
connactoptions.con_Detial.text = value
}
switch modelInfo?.connactDict[indexPath.row].first?.key {
case "联系人"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_profile")
case "电话"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_phone")
case "微信"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_wechat")
case "QQ"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_qq")
case "邮箱"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_email")
default:
break
}
cell = connactoptions
if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! {
cell?.separatorInset = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 0)
}
case 3: cell = tableView.dequeueReusableCell(withIdentifier: "messageHeader")
case 4: cell = tableView.dequeueReusableCell(withIdentifier: "messagesCell")
default: break
}
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.section {
case 0:
switch indexPath.row {
case 0: return 60
case 1: return 100
case 2: return 40
default: return 20
}
case 1:
return detialHeight + 10
case 2:
return 50
case 3:
return 40
case 4:
return 120
default:
return 20
}
}
}
| apache-2.0 |
jdkelley/Udacity-MemeMe | MemeMe/MemeMeUITests/MemeMeUITests.swift | 1 | 1245 | //
// MemeMeUITests.swift
// MemeMeUITests
//
// Created by Joshua Kelley on 3/29/16.
// Copyright © 2016 Joshua Kelley. All rights reserved.
//
import XCTest
class MemeMeUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| mit |
zyuanming/EffectDesignerX | EffectDesignerX/View/Protocols.swift | 1 | 3633 | //
// TabsControlProtocols.swift
// KPCTabsControl
//
// Created by Cédric Foellmi on 15/07/16.
// Licensed under the MIT License (see LICENSE file)
//
import AppKit
@objc public protocol TabsControlDataSource: NSObjectProtocol {
/**
Returns the number of tabs
- parameter control: The instance of the tabs control.
- returns: A unsigned integer indicating the number of tabs to display.
*/
func tabsControlNumberOfTabs(_ control: TabsControl) -> Int
/**
Return the item for the tab at the given index, similarly to a "representedObject" in a cell view.
- parameter control: The instance of the tabs control.
- parameter index: The index of the given item.
- returns: An instance of an object representing the tab.
*/
func tabsControl(_ control: TabsControl, itemAtIndex index: Int) -> AnyObject
/**
Return the title for the tab of the given item
- parameter control: The instance of the tabs control.
- parameter item: The item representing the given tab.
- returns: A string to be used as title of the tab.
*/
func tabsControl(_ control: TabsControl, titleForItem item: AnyObject) -> String
/**
If any, returns an icon for the tab, to be placed to the left side of it.
- parameter control: The instance of the tabs control.
- parameter item: The item representing the given tab.
- returns: An image instance for the icon.
*/
@objc optional func tabsControl(_ control: TabsControl, iconForItem item:AnyObject) -> NSImage?
}
@objc public protocol TabsControlDelegate: NSControlTextEditingDelegate {
/**
* Determine if the tab can be selected.
*
* - parameter tabControl: The instance of the tabs control.
* - parameter item: The item representing the given tab.
*
* - returns: A boolean value indicating whether the tab can be selected or not.
*/
@objc optional func tabsControl(_ control: TabsControl, canSelectItem item: AnyObject) -> Bool
/**
* If implemented, the delegate is informed that the selected tab did change.
* See also TabsControlSelectionDidChangeNotification
*
* - parameter tabControl: The instance of the tabs control.
* - parameter item: The item representing the selected tab.
*/
@objc optional func tabsControlDidChangeSelection(_ control: TabsControl, item: AnyObject)
/**
* Return `true` if you allow the editing of the title of the tab. By default, titles are not editable.
* This method has no effect if the one below is not implemented.
*
* - parameter tabControl: The instance of the tabs control.
* - parameter item: The item representing the given tab.
*
* - returns: A boolean value indicating whether the tab title can be edited or not.
*/
@objc optional func tabsControl(_ control: TabsControl, canEditTitleOfItem item: AnyObject) -> Bool
/**
* If implemented, the delegate is informed that the tab has been renamed to the given title. Again, it is the
* delegate responsability to store the new title.
*
* - parameter tabControl: The instance of the tabs control.
* - parameter newTitle: The new title value.
* - parameter item: The item representing the given tab.
*/
@objc optional func tabsControl(_ control: TabsControl, setTitle newTitle: String, forItem item: AnyObject)
@objc optional func tabsControl(_ control: TabsControl, didCloseItem item: AnyObject)
}
| mit |
laszlokorte/reform-swift | ReformMath/ReformMath/Circle2d.swift | 1 | 581 | //
// Circle2d.swift
// ReformMath
//
// Created by Laszlo Korte on 21.09.15.
// Copyright © 2015 Laszlo Korte. All rights reserved.
//
public struct Circle2d : Equatable {
public let center: Vec2d
public let radius: Double
public init(center: Vec2d, radius: Double) {
self.center = center
self.radius = radius
}
}
public func ==(lhs: Circle2d, rhs: Circle2d) -> Bool {
return lhs.center == rhs.center && lhs.radius == rhs.radius
}
extension Circle2d {
public var circumference : Double {
return 2*Double.TAU*radius
}
}
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/20517-no-stacktrace.swift | 11 | 264 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
{
let a {
{
func b
{
{
}
( [ {
{
{
}
{
}
}
let end = [ {
{
}
var b = [ [ {
class
case c,
let e
| mit |
cnoon/swift-compiler-crashes | crashes-duplicates/13137-getselftypeforcontainer.swift | 11 | 389 | // Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class A {
protocol P {
class A : e <H b
class A : a {
protocol a {
typealias e : e
func
a B T A
}
let a {
class A : {
class A {
protocol g {
protocol g {
class A {
func a(d : e b> ) {
Void{
func g< ) > {
typealias b ) {
| mit |
TeamProxima/predictive-fault-tracker | mobile/SieHack/Pods/Charts/Source/Charts/Data/Implementations/Standard/ChartDataEntryBase.swift | 21 | 2128 | //
// ChartDataEntryBase.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
open class ChartDataEntryBase: NSObject
{
/// the y value
open var y = Double(0.0)
/// optional spot for additional data this Entry represents
open var data: AnyObject?
public override required init()
{
super.init()
}
/// An Entry represents one single entry in the chart.
/// - parameter y: the y value (the actual value of the entry)
public init(y: Double)
{
super.init()
self.y = y
}
/// - parameter y: the y value (the actual value of the entry)
/// - parameter data: Space for additional data this Entry represents.
public init(y: Double, data: AnyObject?)
{
super.init()
self.y = y
self.data = data
}
// MARK: NSObject
open override func isEqual(_ object: Any?) -> Bool
{
if object == nil
{
return false
}
if !(object! as AnyObject).isKind(of: type(of: self))
{
return false
}
if (object! as AnyObject).data !== data && !((object! as AnyObject).data??.isEqual(self.data))!
{
return false
}
if fabs((object! as AnyObject).y - y) > DBL_EPSILON
{
return false
}
return true
}
// MARK: NSObject
open override var description: String
{
return "ChartDataEntryBase, y \(y)"
}
}
public func ==(lhs: ChartDataEntryBase, rhs: ChartDataEntryBase) -> Bool
{
if lhs === rhs
{
return true
}
if !lhs.isKind(of: type(of: rhs))
{
return false
}
if lhs.data !== rhs.data && !lhs.data!.isEqual(rhs.data)
{
return false
}
if fabs(lhs.y - rhs.y) > DBL_EPSILON
{
return false
}
return true
}
| mit |
krimpedance/KRActivityIndicator | Package.swift | 2 | 551 | // swift-tools-version:5.3
import PackageDescription
let package = Package(
name: "KRActivityIndicatorView",
platforms: [.iOS(.v9)],
products: [
.library(
name: "KRActivityIndicatorView",
targets: ["KRActivityIndicatorView"]),
],
targets: [
.target(
name: "KRActivityIndicatorView",
path: "KRActivityIndicatorView"
),
.testTarget(
name: "KRActivityIndicatorViewTests",
path: "KRActivityIndicatorViewTests"
),
]
)
| mit |
qonceptual/QwikHttp | Pod/Classes/QwikHttp.swift | 1 | 21118 | //
// QwikHttp.swift
// QwikHttp
//
// Created by Logan Sease on 1/26/16.
// Copyright © 2016 Logan Sease. All rights reserved.
//
import Foundation
import QwikJson
public typealias BooleanCompletionHandler = (success: Bool) -> Void
/****** REQUEST TYPES *******/
@objc public enum HttpRequestMethod : Int {
case Get = 0, Post, Put, Delete
}
//parameter types
@objc public enum ParameterType : Int
{
case Json = 0, FormEncoded
}
//indicates if the response should be called on the background or main thread
@objc public enum ResponseThread : Int
{
case Main = 0, Background
}
//a delegate used to configure and show a custom loading indicator.
@objc public protocol QwikHttpLoadingIndicatorDelegate
{
@objc func showIndicator(title: String!)
@objc func hideIndicator()
}
//This interceptor protocol is in place so that we can register an interceptor to our class to intercept certain
//responses. This could be useful to check for expired tokens and then retry the request instead of calling the
//handler with the error. This could also allow you to show the login screen when an unautorized response is returned
//using this class will help avoid the need to do this constantly on each api call.
public protocol QwikHttpResponseInterceptor
{
func shouldInterceptResponse(response: NSURLResponse!) -> Bool
func interceptResponse(request : QwikHttp!, handler: (NSData?, NSURLResponse?, NSError?) -> Void)
}
//the request interceptor can be used to intercept requests before they are sent out.
public protocol QwikHttpRequestInterceptor
{
func shouldInterceptRequest(request: QwikHttp!) -> Bool
func interceptRequest(request : QwikHttp!, handler: (NSData?, NSURLResponse?, NSError?) -> Void)
}
//a class to store default values and configuration for quikHttp
@objc public class QwikHttpConfig : NSObject
{
public private(set) static var defaultTimeOut = 40 as Double
public static var defaultCachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
public static var defaultParameterType = ParameterType.Json
public static var defaultLoadingTitle : String? = nil
public static var loadingIndicatorDelegate: QwikHttpLoadingIndicatorDelegate? = nil
public static var responseInterceptor: QwikHttpResponseInterceptor? = nil
public static var responseInterceptorObjc: QwikHttpObjcResponseInterceptor? = nil
public static var requestInterceptor: QwikHttpRequestInterceptor? = nil
public static var requestInterceptorObjc: QwikHttpObjcRequestInterceptor? = nil
public static var defaultResponseThread : ResponseThread = .Main
//ensure timeout > 0
public class func setDefaultTimeOut(timeout: Double!)
{
if(timeout > 0)
{
defaultTimeOut = timeout
}
else
{
defaultTimeOut = 40
}
}
}
//the main request object
public class QwikHttp {
/***** REQUEST VARIABLES ******/
private var urlString : String!
private var httpMethod : HttpRequestMethod!
private var headers : [String : String]!
private var params : [String : AnyObject]!
private var body: NSData?
private var parameterType : ParameterType!
private var responseThread : ResponseThread!
public var avoidResponseInterceptor = false
//response variables
public var responseError : NSError?
public var responseData : NSData?
public var response: NSURLResponse?
public var responseString : NSString?
public var wasIntercepted = false
//class params
private var timeOut : Double!
private var cachePolicy: NSURLRequestCachePolicy!
private var loadingTitle: String?
/**** REQUIRED INITIALIZER*****/
public convenience init(url: String!, httpMethod: HttpRequestMethod!)
{
self.init(url,httpMethod: httpMethod)
}
public init(_ url: String!, httpMethod: HttpRequestMethod!)
{
self.urlString = url
self.httpMethod = httpMethod
self.headers = [:]
self.params = [:]
//set defaults
self.parameterType = QwikHttpConfig.defaultParameterType
self.cachePolicy = QwikHttpConfig.defaultCachePolicy
self.timeOut = QwikHttpConfig.defaultTimeOut
self.loadingTitle = QwikHttpConfig.defaultLoadingTitle
self.responseThread = QwikHttpConfig.defaultResponseThread
}
/**** ADD / SET VARIABLES. ALL RETURN SELF TO ENCOURAGE SINGLE LINE BUILDER TYPE SYNTAX *****/
//add a parameter to the request
public func addParam(key : String!, value: String?) -> QwikHttp
{
if let v = value
{
params[key] = v
}
return self
}
//add a header
public func addHeader(key : String!, value: String?) -> QwikHttp
{
if let v = value
{
headers[key] = v
}
return self
}
//set a title to the loading indicator. Set to nil for no indicator
public func setLoadingTitle(title: String?) -> QwikHttp
{
self.loadingTitle = title
return self
}
//add a single optional URL parameter
public func addUrlParam(key: String!, value: String?) -> QwikHttp
{
guard let param = value else
{
return self
}
//start our URL Parameters
if let _ = urlString.rangeOfString("?")
{
urlString = urlString + "&"
}
else
{
urlString = urlString + "?"
}
urlString = urlString + QwikHttp.paramStringFrom([key : param])
return self
}
//add an array of URL parameters
public func addUrlParams(params: [String: String]!) -> QwikHttp
{
//start our URL Parameters
if let _ = urlString.rangeOfString("?")
{
urlString = urlString + "&"
}
else
{
urlString = urlString + "?"
}
urlString = urlString + QwikHttp.paramStringFrom(params)
return self
}
public func removeUrlParam(key: String!)
{
//get our query items from the url
if #available(OSX 10.10, *)
{
if let urlComponents = NSURLComponents(string: urlString), items = urlComponents.queryItems
{
//get a new array of query items by removing any with the key we want
let newItems = items.filter { $0.name == key }
//reconstruct our url if we removed anything
if(newItems.count != items.count)
{
urlComponents.queryItems = newItems
urlString = urlComponents.string
}
}
}
}
//set a quikJson into the request. Will serialize to json and set the content type.
public func setObject(object: QwikJson?) -> QwikHttp
{
if let qwikJson = object, params = qwikJson.toDictionary() as? [String : AnyObject]
{
self.addParams(params)
self.setParameterType(.Json)
}
return self
}
//set an array of objects to the request body serialized as json objects.
public func setObjects<Q : QwikJson>(objects: [Q]?, toModelClass modelClass: Q.Type) -> QwikHttp
{
if let array = objects, params = QwikJson.jsonArrayFromArray(array, ofClass: modelClass )
{
do{
let data = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
self.setBody(data)
self.addHeader("Content-Type", value: "application/json")
}
catch _ as NSError {}
}
return self
}
//add an list of parameters
public func addParams(params: [String: AnyObject]!) -> QwikHttp
{
self.params = combinedDictionary(self.params, with: params)
return self
}
//add a list of headers
public func addHeaders(headers: [String: String]!) -> QwikHttp
{
self.headers = combinedDictionary(self.headers, with: headers) as! [String : String]
return self
}
//set the body directly
public func setBody(body : NSData!) -> QwikHttp
{
self.body = body
return self;
}
//set the parameter type
public func setParameterType(parameterType : ParameterType!) -> QwikHttp
{
self.parameterType = parameterType
return self;
}
//set the cache policy
public func setCachePolicy(policy: NSURLRequestCachePolicy!) -> QwikHttp
{
cachePolicy = policy
return self
}
//set the request time out
public func setTimeOut(timeOut: Double!) -> QwikHttp
{
self.timeOut = timeOut
return self
}
public func setResponseThread(responseThread: ResponseThread!) -> QwikHttp
{
self.responseThread = responseThread
return self
}
/********* RESPONSE HANDLERS / SENDING METHODS *************/
//get an an object of a generic type back
public func getResponse<T : QwikDataConversion>(type: T.Type, _ handler : (T?, NSError?, QwikHttp!) -> Void)
{
HttpRequestPooler.sendRequest(self) { (data, response, error) -> Void in
//check for an error
if let e = error
{
self.determineThread({ () -> () in
handler(nil,e, self)
})
}
else
{
//try to deserialize our object
if let t : T = T.fromData(data)
{
self.determineThread({ () -> () in
handler(t,nil,self)
})
}
//error if we could deserialize
else
{
self.determineThread({ () -> () in
handler(nil,NSError(domain: "QwikHttp", code: 500, userInfo: ["Error" : "Could not parse response"]), self)
})
}
}
}
}
//get an array of a generic type back
public func getArrayResponse<T : QwikDataConversion>(type: T.Type, _ handler : ([T]?, NSError?, QwikHttp!) -> Void)
{
HttpRequestPooler.sendRequest(self) { (data, response, error) -> Void in
//check for error
if let e = error
{
self.determineThread({ () -> () in
handler(nil,e, self)
})
}
else
{
//convert the response to an array of T
if let t : [T] = T.arrayFromData(data)
{
self.determineThread({ () -> () in
handler(t,nil,self)
})
}
else
{
//error if we could not deserialize
self.determineThread({ () -> () in
handler(nil,NSError(domain: "QwikHttp", code: 500, userInfo: ["Error" : "Could not parse response"]), self)
})
}
}
}
}
//Send the request with a simple boolean handler, which is optional
public func send( handler: BooleanCompletionHandler? = nil)
{
HttpRequestPooler.sendRequest(self) { (data, response, error) -> Void in
if let booleanHandler = handler
{
if let _ = error
{
self.determineThread({ () -> () in
booleanHandler(success: false)
})
}
else
{
self.determineThread({ () -> () in
booleanHandler(success: true)
})
}
}
}
}
//a helper method to duck the response interceptor. Can be useful for cases like logout which
//could lead to infinite recursion
public func setAvoidResponseInterceptor(avoid : Bool!) -> QwikHttp!
{
self.avoidResponseInterceptor = true
return self
}
//this method is primarily used for the response interceptor as any easy way to restart the request
public func resend(handler: (NSData?,NSURLResponse?, NSError? ) -> Void)
{
HttpRequestPooler.sendRequest(self, handler: handler)
}
//reset our completion handlers and response data
public func reset()
{
self.response = nil
self.responseString = nil
self.responseData = nil
self.responseError = nil
self.responseData = nil
self.wasIntercepted = false
}
/**** HELPERS ****/
//combine two dictionaries
private func combinedDictionary(from: [String:AnyObject]!, with: [String:AnyObject]! ) -> [String:AnyObject]!
{
var result = from
//ensure someone didn't pass us nil on accident
if(with == nil)
{
return result
}
for(key, value) in with
{
result[key] = value
}
return result
}
//create a url parameter string
class func paramStringFrom(from: [String : String]!) -> String!
{
var string = ""
var first = true
for(key,value) in from
{
if !first
{
string = string + "&"
}
if let encoded = value.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
{
string = string + key + "=" + encoded
}
first = false
}
return string
}
//determine if we should run on the main or background thread and run it conditionally
private func determineThread(code: () -> () )
{
if(self.responseThread == .Main)
{
dispatch_async(dispatch_get_main_queue()) {
code()
}
}
else
{
code()
}
}
//run on the main thread
private class func mainThread(code: () -> () )
{
dispatch_async(dispatch_get_main_queue()) {
code()
}
}
}
//this class is used to pool our requests and also to avoid the need to retain our QwikRequest objects
private class HttpRequestPooler
{
class func sendRequest(requestParams : QwikHttp!, handler: (NSData?, NSURLResponse?, NSError?) -> Void)
{
//make sure our request url is valid
guard let url = NSURL(string: requestParams.urlString)
else
{
handler(nil,nil,NSError(domain: "QwikHTTP", code: 500, userInfo:["Error" : "Invalid URL"]))
return
}
//see if this request should be intercepted and if so call the interceptor.
//don't worry about a completion handler since this should be called by the interceptor
if let interceptor = QwikHttpConfig.requestInterceptor where interceptor.shouldInterceptRequest(requestParams) && !requestParams.wasIntercepted
{
requestParams.wasIntercepted = true
interceptor.interceptRequest(requestParams, handler: handler)
return
}
//create our http request
let request = NSMutableURLRequest(URL: url, cachePolicy: requestParams.cachePolicy, timeoutInterval: requestParams.timeOut)
//set up our http method and add headers
request.HTTPMethod = HttpRequestPooler.paramTypeToString(requestParams.httpMethod)
for(key, value) in requestParams.headers
{
request.addValue(value, forHTTPHeaderField: key)
}
//set up our parameters
if let body = requestParams.body
{
request.HTTPBody = body
}
else if requestParams.parameterType == .FormEncoded && requestParams.params.count > 0
{
//convert parameters to form encoded values and set to body
if let params = requestParams.params as? [String : String]
{
request.HTTPBody = QwikHttp.paramStringFrom(params).dataUsingEncoding(NSUTF8StringEncoding)
//set the request type headers
//application/x-www-form-urlencoded
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
//if we couldn't encode the values, then perhaps json was passed in unexpectedly, so try to parse it as json.
else
{
requestParams.setParameterType(.Json)
}
}
//try json parsing, note that formEncoding could have changed the type if there was an error, so don't use an else if
if requestParams.parameterType == .Json && requestParams.params.count > 0
{
//convert parameters to json string and form and set to body
do {
let data = try NSJSONSerialization.dataWithJSONObject(requestParams.params, options: NSJSONWritingOptions(rawValue: 0))
request.HTTPBody = data
}
catch let JSONError as NSError {
handler(nil,nil,JSONError)
return
}
//set the request type headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
}
//show our spinner
var showingSpinner = false
if let title = requestParams.loadingTitle, indicatorDelegate = QwikHttpConfig.loadingIndicatorDelegate
{
indicatorDelegate.showIndicator(title)
showingSpinner = true
}
//send our request and do a bunch of common stuff before calling our response handler
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: { (responseData, urlResponse, error) -> Void in
//set the values straight to the request object so we can read it if needed.
requestParams.responseData = responseData
requestParams.responseError = error
//set our response string
if let responseString = self.getResponseString(responseData)
{
requestParams.responseString = responseString
}
//hide our spinner
if let indicatorDelegate = QwikHttpConfig.loadingIndicatorDelegate where showingSpinner == true
{
indicatorDelegate.hideIndicator()
}
//check the responseCode to make sure its valid
if let httpResponse = urlResponse as? NSHTTPURLResponse {
requestParams.response = httpResponse
//see if we are configured to use an interceptor and if so, check it to see if we should use it
if let interceptor = QwikHttpConfig.responseInterceptor where !requestParams.wasIntercepted && interceptor.shouldInterceptResponse(httpResponse) && !requestParams.avoidResponseInterceptor
{
//call the interceptor and return. The interceptor will call our handler.
requestParams.wasIntercepted = true
interceptor.interceptResponse(requestParams, handler: handler)
return
}
//error for invalid response
//in order to be considered successful the response must be in the 200's
if httpResponse.statusCode / 100 != 2 && error == nil
{
handler(responseData, urlResponse, NSError(domain: "QwikHttp", code: httpResponse.statusCode, userInfo: ["Error": "Error Response Code"]))
return
}
}
handler(responseData, urlResponse, error)
})
task.resume()
}
//convert our enum to a string used for the request
private class func paramTypeToString(type: HttpRequestMethod) -> String!
{
switch(type)
{
case HttpRequestMethod.Post:
return "POST"
case HttpRequestMethod.Put:
return "PUT"
case HttpRequestMethod.Get:
return "GET"
case HttpRequestMethod.Delete:
return "DELETE"
}
}
//a helper to to return an optional string from our ns data
class func getResponseString(data : NSData?) -> String?
{
if let d = data{
return String(data: d, encoding: NSUTF8StringEncoding)
}
else
{
return nil
}
}
}
| mit |
yuanziyuer/XLPagerTabStrip | Example/Example/TwitterExampleViewController.swift | 2 | 2982 | // TwitterExampleViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import XLPagerTabStrip
class TwitterExampleViewController: TwitterPagerTabStripViewController {
var isReload = false
override func viewControllersForPagerTabStrip(pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
let child_1 = TableChildExampleViewController(style: .Plain, itemInfo: "TableView")
let child_2 = ChildExampleViewController(itemInfo: "View")
let child_3 = TableChildExampleViewController(style: .Grouped, itemInfo: "TableView 2")
let child_4 = ChildExampleViewController(itemInfo: "View 2")
let child_5 = TableChildExampleViewController(style: .Plain, itemInfo: "TableView 3")
let child_6 = ChildExampleViewController(itemInfo: "View 3")
let child_7 = TableChildExampleViewController(style: .Grouped, itemInfo: "TableView 4")
let child_8 = ChildExampleViewController(itemInfo: "View 4")
guard isReload else {
return [child_1, child_2, child_3, child_4, child_5, child_6, child_7, child_8]
}
var childViewControllers = [child_1, child_2, child_3, child_4, child_6, child_7, child_8]
for (index, _) in childViewControllers.enumerate(){
let nElements = childViewControllers.count - index
let n = (Int(arc4random()) % nElements) + index
if n != index{
swap(&childViewControllers[index], &childViewControllers[n])
}
}
let nItems = 1 + (rand() % 8)
return Array(childViewControllers.prefix(Int(nItems)))
}
@IBAction func reloadTapped(sender: AnyObject) {
isReload = true
reloadPagerTabStripView()
}
}
| mit |
KosyanMedia/Aviasales-iOS-SDK | AviasalesSDKTemplate/Source/HotelsSource/Controls/HLToastView.swift | 1 | 3025 | import UIKit
import Foundation
@objcMembers
class HLToastView: UIView {
var presented: Bool = false
var animated: Bool = false
var needHideByTimeout: Bool = true
var hideAfterTime: TimeInterval = 1.0
fileprivate let defaultWidth: CGFloat = 240.0
fileprivate let defaultShowDuration: TimeInterval = 0.4
fileprivate let defaultHideDuration: TimeInterval = 0.8
fileprivate var hideTimer: Timer?
@IBOutlet fileprivate(set) weak var iconView: UIImageView!
@IBOutlet fileprivate(set) weak var titleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
self.initialize()
}
// MARK: - Internal methods
func show(_ onView: UIView, animated: Bool) {
onView.addSubview(self)
self.translatesAutoresizingMaskIntoConstraints = false
self.alpha = 0.0
let constraintWidth = NSLayoutConstraint.constraints(withVisualFormat: "H:[selfView(selfWidth)]", options: .alignAllCenterY, metrics: ["selfWidth": defaultWidth], views: ["selfView": self])
onView.addConstraints(constraintWidth)
let constraintCenterY = NSLayoutConstraint(item: self, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: .equal, toItem: superview, attribute: .centerY, multiplier: 1, constant: 0)
onView.addConstraint(constraintCenterY)
let constraintCenterX = NSLayoutConstraint(item: self, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: .equal, toItem: superview, attribute: .centerX, multiplier: 1, constant: 0)
onView.addConstraint(constraintCenterX)
let duration = (animated ? self.defaultShowDuration : 0.0)
UIView.animate(withDuration: duration, delay: 0.0, options: UIView.AnimationOptions(),
animations: { () -> Void in
self.alpha = 1.0
}, completion: { (finished) -> Void in
if self.needHideByTimeout {
self.hideTimer = Timer.scheduledTimer(timeInterval: self.hideAfterTime, target: self, selector: #selector(HLToastView.onTimer), userInfo: nil, repeats: false)
}
})
self.presented = true
}
func dismiss(_ duration: TimeInterval) {
if self.animated {
return
}
self.animated = true
let options: UIView.AnimationOptions = UIView.AnimationOptions.beginFromCurrentState
UIView.animate(withDuration: duration, delay: 0.0, options: options,
animations: { () -> Void in
self.alpha = 0.0
}, completion: { (finished) -> Void in
self.removeFromSuperview()
self.presented = false
self.animated = false
})
}
func timeredDismiss() {
self.dismiss(0.8)
}
func manualDismiss() {
self.dismiss(0.3)
}
@objc func onTimer() {
self.timeredDismiss()
}
// MARK: - Private methods
fileprivate func initialize() {
self.layer.cornerRadius = 10.0
self.layer.masksToBounds = true
}
}
| mit |
jameshuynh/JHDownloadManager | Example/JHDownloadManager/AppDelegate.swift | 1 | 2362 | //
// AppDelegate.swift
// JHDownloadManager
//
// Created by James Huynh on 02/21/2016.
// Copyright (c) 2016 James Huynh. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
let navigationController = UINavigationController(rootViewController: DownloadViewController())
self.window?.rootViewController = navigationController
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
artemkalinovsky/SwiftyPiper | SwiftyPiper/Model/Player/PlayerDelegate.swift | 1 | 395 | //
// PlayerDelegate.swift
// SwiftyPiper
//
// Created by Artem Kalinovsky on 17/02/2016.
// Copyright © 2016 Artem Kalinovsky. All rights reserved.
//
import Foundation
protocol PlayerDelegate:class {
func playerDidFailWithStatus(player: Player, status: String) throws
func playerDidChangeReadyToPlayStatus(status: String)
func playerDidChangedCurrentItem(player: Player)
}
| gpl-3.0 |
llbbl/coffee-timer | coffee timer/ViewController.swift | 1 | 1648 | //
// ViewController.swift
// coffee timer
//
// Created by Logan Lindquist on 6/18/15.
// Copyright (c) 2015 Logan Lindquist. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: UILabel!
@IBOutlet weak var slider: UISlider!
@IBOutlet weak var progress: UIProgressView!
var timerModel: TimerModel!
override func viewDidLoad() {
super.viewDidLoad()
println("view is loaded. ")
view.backgroundColor = .orangeColor()
// Do any additional setup after loading the view, typically from a nib.
setupModel()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func shouldAutorotate() -> Bool {
return false
}
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.Portrait.rawValue)
}
func setupModel(){
timerModel = TimerModel(coffeeName: "Colombian Coffee", duration: 240)
}
@IBAction func buttonWasPressed(sender: AnyObject) {
println("button was pressed")
let date = NSDate()
//update the label
label.text = "button pressed @ \(date)"
}
@IBAction func sliderValueChanged(sender: AnyObject) {
println("Slider value changed to \(self.slider.value)")
//update our progreess view to match slider
progress.progress = slider.value
}
}
| mit |
brentdax/swift | test/SILOptimizer/definite_init_inout_super_init.swift | 7 | 321 | // RUN: %target-swift-frontend -emit-sil -verify %s -o /dev/null
class B {
init(x: inout Int) {}
}
class A : B {
let x: Int // expected-note {{change 'let' to 'var' to make it mutable}}
init() {
self.x = 12
super.init(x: &x) // expected-error {{immutable value 'self.x' must not be passed inout}}
}
}
| apache-2.0 |
4np/UitzendingGemist | UitzendingGemist/LiveViewController.swift | 1 | 5841 | //
// LiveViewController.swift
// UitzendingGemist
//
// Created by Jeroen Wesbeek on 21/07/16.
// Copyright © 2016 Jeroen Wesbeek. All rights reserved.
//
import Foundation
import UIKit
import AVKit
import NPOKit
import CocoaLumberjack
class LiveViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
@IBOutlet weak var liveCollectionView: UICollectionView!
private var guides: [NPOLive: [NPOBroadcast]]? {
didSet {
guard let guides = guides, let oldValue = oldValue, oldValue.count > 0 else {
self.liveCollectionView.reloadData()
return
}
// refresh cells rather than reloading to make the UI behave better
for (index, channel) in NPOLive.all.enumerated() {
let path = IndexPath(row: index, section: 0)
if let cell = self.liveCollectionView.cellForItem(at: path) as? LiveCollectionViewCell {
cell.configure(withLiveChannel: channel, andGuide: guides[channel])
}
}
}
}
// MARK: Lifecycle
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
fetchGuides()
// observe when we are foregrounded
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillEnterForeground), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self)
}
@objc private func applicationWillEnterForeground() {
fetchGuides()
}
// MARK: Networking
private func fetchGuides() {
NPOManager.sharedInstance.getGuides(forChannels: NPOLive.all, onDate: Date()) { [weak self] guides, errors in
// log errors if we have any
for (channel, error) in errors ?? [NPOLive: NPOError]() {
DDLogError("Could not get guide for '\(channel)' (\(error))")
}
self?.guides = guides
}
}
// MARK: UICollectionViewDataSource
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return NPOLive.all.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCells.live.rawValue, for: indexPath)
guard let liveCell = cell as? LiveCollectionViewCell, indexPath.row >= 0 && indexPath.row < NPOLive.all.count else {
return cell
}
let channel = NPOLive.all[indexPath.row]
liveCell.configure(withLiveChannel: channel, andGuide: self.guides?[channel])
return liveCell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard indexPath.row >= 0 && indexPath.row < NPOLive.all.count, let cell = collectionView.cellForItem(at: indexPath) as? LiveCollectionViewCell else {
return
}
let channel = NPOLive.all[indexPath.row]
var channelDescription = ""
if let current = cell.currentLabel.text {
channelDescription += current
}
if let upcoming = cell.upcommingLabel.text {
if channelDescription != "" { channelDescription += ", " }
channelDescription += upcoming
}
self.play(liveChannel: channel, channelImage: cell.channelImageView.image, channelDescription: channelDescription)
}
// MARK: Playing
fileprivate func play(liveChannel channel: NPOLive, channelImage: UIImage?, channelDescription: String?) {
// show progress hud
self.view.startLoading()
// live streams do not have a separate closed captioning resource, instead
// they have a different (and unfortunately often a lower quality) stream
let closedCaptioningEnabled = UserDefaults.standard.bool(forKey: UitzendingGemistConstants.closedCaptioningEnabledKey)
let liveChannel = closedCaptioningEnabled ? channel.sdhChannel() : channel
NPOManager.sharedInstance.getVideoStream(forLiveChannel: liveChannel) { [weak self] url, error in
// hide progress hud
self?.view.stopLoading()
guard let url = url else {
if let alternativeChannel = channel.configuration.alternativeChannel {
DDLogDebug("No stream for channel \(channel.configuration.name), switching to alternative channel \(alternativeChannel.configuration.name)")
self?.play(liveChannel: alternativeChannel, channelImage: nil, channelDescription: nil)
} else {
DDLogError("Could not play live stream (\(String(describing: error)))")
}
return
}
let playerViewController = NPOPlayerViewController()
let configuration = channel.configuration
let metadata: [String: Any?] = [
AVMetadataCommonKeyTitle: configuration.name,
AVMetadataCommonKeyDescription: channelDescription,
AVMetadataCommonKeyArtwork: channelImage
]
self?.present(playerViewController, animated: true) {
playerViewController.play(videoStream: url, externalMetadata: metadata)
}
}
}
}
| apache-2.0 |
KittenYang/GooeyTabbar | GooeyTabbar/ViewController.swift | 1 | 472 | //
// ViewController.swift
// GooeyTabbar
//
// Created by KittenYang on 11/16/15.
// Copyright © 2015 KittenYang. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
var menu : TabbarMenu!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
menu = TabbarMenu(texture: .withBlur(blurStyle: .dark) ,tabbarHeight: 40.0, toTop: 200)
}
}
| mit |
Mioke/SwiftArchitectureWithPOP | ComponentizeDemo/Auth/Source/Auth.swift | 1 | 1620 | import Foundation
import MIOSwiftyArchitecture
import AuthProtocol
class AuthModule: ModuleProtocol, AuthServiceProtocol {
static var moduleIdentifier: ModuleIdentifier {
return .auth
}
required init() { }
func moduleDidLoad(with manager: ModuleManager) {
}
func authenticate(completion: @escaping (User) -> ()) throws {
DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
let user = User(id: "15780")
ModuleManager.default.beginUserSession(with: user.id)
self.markAsReleasing()
completion(user)
}
}
func refreshAuthenticationIfNeeded(completion: @escaping (User) -> ()) {
if let previousUID = AppContext.standard.previousLaunchedUserId {
let previousUser = User(id: previousUID)
let previousContext = AppContext(user: previousUser)
// get token from previous context data center, like:
// let credential = previousContext.dataCenter.object(with: previousUID, type: Credential.Type)
print(previousContext)
// and then do some refresh token logic here.
}
}
func deauthenticate(completion: @escaping (Error?) -> Void) {
}
}
extension AuthModule: ModuleInitiatorProtocol {
static var identifier: String { moduleIdentifier }
static var priority: Initiator.Priority { .high }
static var dependencies: [String] { [] }
static var operation: Initiator.Operation {
return {
print("Auth module initiator operation running.")
}
}
}
| mit |
githubdelegate/ASToast | ASToast/ASToast.swift | 1 | 15794 | //
// ASToast.swift
// ASToast
//
// Created by Abdullah Selek on 10/06/15.
// Copyright (c) 2015 Abdullah Selek. All rights reserved.
//
import UIKit
import QuartzCore
// MARK: Constants
struct Constants {
// duration of view on screen
static let ASToastDuration = NSTimeInterval(3)
// view appearance
static let ASToastMaxWidth = CGFloat(0.8)
static let ASToastMaxHeight = CGFloat(0.8)
static let ASToastHorizontalPadding = CGFloat(10)
static let ASToastVerticalPadding = CGFloat(10)
static let ASToastCornerRadius = CGFloat(10)
static let ASToastOpacity = CGFloat(0.8)
static let ASToastFontSize = CGFloat(16)
static let ASToastFadeDuration = NSTimeInterval(0.3)
static let ASToastMaxTitleLines = 0
static let ASToastMaxMessageLines = 0
// value between 0.0 and 1.0
static let ASToastViewAlpha = CGFloat(0.0)
// shadow appearance
static let ASToastDisplayShadow = true
static let ASToastShadowOpacity = Float(0.8)
static let ASToastShadowRadius = CGFloat(5.0)
static var ASToastShadowOffset: CGSize = CGSize(width: 3.0, height: 3.0)
// change visibility of view
static let ASToastHidesOnTap = true
// image view size
static let ASToastImageViewWidth = CGFloat(80.0)
static let ASToastImageViewHeight = CGFloat(80.0)
// activity
static let ASToastActivityWidth = CGFloat(100.0)
static let ASToastActivityHeight = CGFloat(100.0)
static let ASToastActivityDefaultPosition = ASToastPosition.ASToastPositionCenter
}
enum ASToastPosition: String {
case ASToastPositionTop = "ASToastPositionTop",
ASToastPositionCenter = "ASToastPositionCenter",
ASToastPositionBotom = "ASToastPositionBotom"
}
private var timer: NSTimer!
private var activityView: UIView!
extension UIView {
// MARK: Make toast methods
func makeToast(message: String) {
makeToast(message, duration: Constants.ASToastDuration, position: nil)
}
func makeToast(message: String, duration: NSTimeInterval, position: AnyObject?) {
var toastView = self.toastView(message, title: "", image: nil)
self.showToast(toastView, duration: duration, position: position)
}
func makeToast(message: String, duration: NSTimeInterval, position: AnyObject?, title: String) {
var toastView = self.toastView(message, title: title, image: nil)
self.showToast(toastView, duration: duration, position: position)
}
func makeToast(message: String, duration: NSTimeInterval, position: AnyObject?, image: UIImage!) {
var toastView = self.toastView(message, title: "", image: image)
self.showToast(toastView, duration: duration, position: position)
}
func makeToast(message: String, duration: NSTimeInterval, position: AnyObject?, title: String, image: UIImage!) {
var toastView = self.toastView(message, title: title, image: image)
self.showToast(toastView, duration: duration, position: position)
}
// MARK: Toast view main methods
func showToast(toastView: UIView!) {
showToast(toastView, duration: Constants.ASToastDuration, position: nil)
}
func showToast(toastView: UIView!, duration: NSTimeInterval!, position: AnyObject?) {
createAndShowToast(toastView, duration: duration, position: position)
}
private func createAndShowToast(toastView: UIView!, duration: NSTimeInterval!, position: AnyObject?) {
toastView.center = centerPointForPosition(position, toastView: toastView)
toastView.alpha = Constants.ASToastViewAlpha
if Constants.ASToastHidesOnTap {
var tapRecognizer: UITapGestureRecognizer! = UITapGestureRecognizer(target: toastView, action: "handleToastTapped:")
toastView.addGestureRecognizer(tapRecognizer)
toastView.userInteractionEnabled = true
toastView.exclusiveTouch = true
}
timer = NSTimer.scheduledTimerWithTimeInterval(duration, target: self, selector: "toastTimerDidFinish:", userInfo: toastView, repeats: false)
self.addSubview(toastView)
UIView.animateWithDuration(Constants.ASToastDuration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut | UIViewAnimationOptions.AllowUserInteraction, animations: { () -> Void in
toastView.alpha = 1.0
}) { (Bool) -> Void in
}
}
private func hideToast(toastView: UIView!) {
UIView.animateWithDuration(Constants.ASToastFadeDuration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn | UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in
toastView.alpha = 0.0
}) { (Bool) -> Void in
toastView.removeFromSuperview()
}
}
private func toastView(message: String, title: String, image: UIImage?) -> UIView? {
// check parameters
if message.isEmpty && title.isEmpty && image == nil {
return nil
}
// ui elements of toast
var messageLabel: UILabel!
var titleLabel: UILabel!
var imageView: UIImageView!
var toastView: UIView! = UIView()
toastView.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleBottomMargin
toastView.layer.cornerRadius = Constants.ASToastCornerRadius
// check if shadow needed
if Constants.ASToastDisplayShadow == true {
toastView.layer.shadowColor = UIColor.blackColor().CGColor
toastView.layer.shadowOpacity = Constants.ASToastShadowOpacity
toastView.layer.shadowRadius = Constants.ASToastShadowRadius
toastView.layer.shadowOffset = Constants.ASToastShadowOffset
}
// set toastView background color
toastView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(Constants.ASToastOpacity)
// check image
if(image != nil) {
imageView = UIImageView(image: image)
imageView.contentMode = UIViewContentMode.ScaleAspectFit
imageView.frame = CGRectMake(Constants.ASToastHorizontalPadding, Constants.ASToastVerticalPadding, Constants.ASToastImageViewWidth, Constants.ASToastImageViewHeight)
}
var imageWidth, imageHeight, imageLeft: CGFloat!
// the imageView frame values will be used to size & position the other views
if(imageView != nil) {
imageWidth = imageView.bounds.size.width;
imageHeight = imageView.bounds.size.height;
imageLeft = Constants.ASToastHorizontalPadding
} else {
imageWidth = 0.0
imageHeight = 0.0
imageLeft = 0.0
}
// check title if not empty create title label
if !title.isEmpty {
titleLabel = UILabel()
titleLabel.numberOfLines = Constants.ASToastMaxTitleLines
titleLabel.font = UIFont.boldSystemFontOfSize(Constants.ASToastFontSize)
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.textColor = UIColor.whiteColor()
titleLabel.backgroundColor = UIColor.clearColor()
titleLabel.alpha = 1.0
titleLabel.text = title
// set size the title label according to the lenth of title text
var maxSizeTitle = CGSizeMake((self.bounds.size.width * Constants.ASToastMaxWidth) - imageWidth, self.bounds.size.height * Constants.ASToastMaxHeight)
var expectedSizeTitle: CGSize! = sizeForString(title, font: titleLabel.font, constrainedSize: maxSizeTitle, lineBreakMode: titleLabel.lineBreakMode)
titleLabel.frame = CGRectMake(0.0, 0.0, expectedSizeTitle.width, expectedSizeTitle.height)
}
// check message string if not empty create message label
if !message.isEmpty {
messageLabel = UILabel()
messageLabel.numberOfLines = Constants.ASToastMaxMessageLines
messageLabel.font = UIFont.systemFontOfSize(Constants.ASToastFontSize)
messageLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping
messageLabel.textColor = UIColor.whiteColor()
messageLabel.backgroundColor = UIColor.clearColor()
messageLabel.alpha = 1.0
messageLabel.text = message
// set size the message label according to the lenth of message text
var maxSizeMessage = CGSizeMake((self.bounds.size.width * Constants.ASToastMaxWidth) - imageWidth, self.bounds.size.height * Constants.ASToastMaxHeight)
var expectedSizeMessage: CGSize! = sizeForString(message, font: messageLabel.font, constrainedSize: maxSizeMessage, lineBreakMode: messageLabel.lineBreakMode)
messageLabel.frame = CGRectMake(0.0, 0.0, expectedSizeMessage.width, expectedSizeMessage.height)
}
// title label frame values
var titleWidth, titleHeight, titleTop, titleLeft: CGFloat!
if titleLabel != nil {
titleWidth = titleLabel.bounds.size.width
titleHeight = titleLabel.bounds.size.height
titleTop = Constants.ASToastVerticalPadding
titleLeft = imageLeft + imageWidth + Constants.ASToastHorizontalPadding
} else {
titleWidth = 0.0
titleHeight = 0.0
titleTop = 0.0
titleLeft = 0.0
}
// message label frame values
var messageWidth, messageHeight, messageLeft, messageTop: CGFloat!
if messageLabel != nil {
messageWidth = messageLabel.bounds.size.width
messageHeight = messageLabel.bounds.size.height
messageLeft = imageLeft + imageWidth + Constants.ASToastHorizontalPadding
messageTop = titleTop + titleHeight + Constants.ASToastVerticalPadding
} else {
messageWidth = 0.0
messageHeight = 0.0
messageLeft = 0.0
messageTop = 0.0
}
var longerWidth = max(titleWidth, messageWidth)
var longerLeft = max(titleLeft, messageLeft)
// toastView frames
var toastViewWidth = max(imageWidth + (Constants.ASToastHorizontalPadding * 2), (longerLeft + longerWidth + Constants.ASToastHorizontalPadding))
var toastViewHeight = max(messageTop + messageHeight + Constants.ASToastVerticalPadding, (imageHeight + (Constants.ASToastVerticalPadding * 2)))
toastView.frame = CGRectMake(0.0, 0.0, toastViewWidth, toastViewHeight)
if titleLabel != nil {
titleLabel.frame = CGRectMake(titleLeft, titleTop, titleWidth, titleHeight)
toastView.addSubview(titleLabel)
}
if messageLabel != nil {
messageLabel.frame = CGRectMake(messageLeft, messageTop, messageWidth, messageHeight)
toastView.addSubview(messageLabel)
}
if imageView != nil {
toastView.addSubview(imageView)
}
return toastView
}
// MARK: Toast view events
func toastTimerDidFinish(timer: NSTimer) {
self.hideToast(timer.userInfo as? UIView!)
}
func handleToastTapped(recognizer: UITapGestureRecognizer) {
timer.invalidate()
hideToast(recognizer.view)
}
// MARK: Toast activity methods
func makeToastActivity() {
makeToastActivity(Constants.ASToastActivityDefaultPosition.rawValue)
}
private func makeToastActivity(position: AnyObject) {
activityView = UIView(frame: CGRectMake(0.0, 0.0, Constants.ASToastActivityWidth, Constants.ASToastActivityHeight))
activityView.center = centerPointForPosition(position, toastView: activityView)
activityView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(Constants.ASToastOpacity)
activityView.alpha = Constants.ASToastViewAlpha
activityView.autoresizingMask = UIViewAutoresizing.FlexibleLeftMargin | UIViewAutoresizing.FlexibleRightMargin |
UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleBottomMargin
activityView.layer.cornerRadius = Constants.ASToastCornerRadius
if Constants.ASToastDisplayShadow {
activityView.layer.shadowColor = UIColor.blackColor().CGColor
activityView.layer.shadowOpacity = Constants.ASToastShadowOpacity
activityView.layer.shadowRadius = Constants.ASToastShadowRadius
activityView.layer.shadowOffset = Constants.ASToastShadowOffset
}
var activityIndicatorView: UIActivityIndicatorView! = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
activityIndicatorView.center = CGPointMake(activityView.bounds.size.width / 2, activityView.bounds.size.height / 2)
activityView.addSubview(activityIndicatorView)
activityIndicatorView.startAnimating()
self.addSubview(activityView)
UIView.animateWithDuration(Constants.ASToastDuration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
activityView.alpha = 1.0
}, completion: nil)
}
func hideToastActivity() {
if activityView != nil {
UIView.animateWithDuration(Constants.ASToastFadeDuration, delay: 0.0, options: UIViewAnimationOptions.CurveEaseIn | UIViewAnimationOptions.BeginFromCurrentState, animations: { () -> Void in
activityView.alpha = 0.0
}, completion: { (Bool) -> Void in
activityView.removeFromSuperview()
})
}
}
// MARK: Helpers
private func centerPointForPosition(point: AnyObject?, toastView: UIView!) -> CGPoint {
if point != nil {
if point!.isKindOfClass(NSString) {
if point!.caseInsensitiveCompare(ASToastPosition.ASToastPositionTop.rawValue) == NSComparisonResult.OrderedSame {
return CGPointMake(self.bounds.size.width / 2, (toastView.frame.size.height / 2) + Constants.ASToastVerticalPadding)
} else if point!.caseInsensitiveCompare(ASToastPosition.ASToastPositionCenter.rawValue) == NSComparisonResult.OrderedSame {
return CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2)
}
} else if point!.isKindOfClass(NSValue) {
return point!.CGPointValue()
}
}
// default bottom option
return CGPointMake(self.bounds.size.width / 2, (self.bounds.size.height - (toastView.frame.size.height / 2)) - Constants.ASToastVerticalPadding)
}
private func sizeForString(text: NSString, font: UIFont, constrainedSize: CGSize, lineBreakMode: NSLineBreakMode) -> CGSize {
if text.respondsToSelector("boundingRectWithSize:options:attributes:context:") {
var paragraphStyle: NSMutableParagraphStyle! = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = lineBreakMode
var attributes: Dictionary = [NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle]
var boundingRect: CGRect! = text.boundingRectWithSize(constrainedSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: attributes, context: nil)
return CGSizeMake(boundingRect.size.width, boundingRect.size.height)
}
return CGSizeMake(0.0, 0.0)
}
} | mit |
atl009/WordPress-iOS | WordPress/Classes/ViewRelated/NUX/LoginEpilogueSectionHeader.swift | 2 | 119 | import UIKit
class LoginEpilogueSectionHeader: UITableViewHeaderFooterView {
@IBOutlet var titleLabel: UILabel?
}
| gpl-2.0 |
edx/edx-app-ios | Source/DiscussionNewPostViewController.swift | 1 | 18880 | //
// DiscussionNewPostViewController.swift
// edX
//
// Created by Tang, Jeff on 6/1/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
struct DiscussionNewThread {
let courseID: String
let topicID: String
let type: DiscussionThreadType
let title: String
let rawBody: String
}
protocol DiscussionNewPostViewControllerDelegate : AnyObject {
func newPostController(controller : DiscussionNewPostViewController, addedPost post: DiscussionThread)
}
public class DiscussionNewPostViewController: UIViewController, UITextViewDelegate, MenuOptionsViewControllerDelegate, InterfaceOrientationOverriding {
public typealias Environment = DataManagerProvider & NetworkManagerProvider & OEXRouterProvider & OEXAnalyticsProvider
private let minBodyTextHeight : CGFloat = 66 // height for 3 lines of text
private let environment: Environment
private let growingTextController = GrowingTextViewController()
private let insetsController = ContentInsetsController()
@IBOutlet private var scrollView: UIScrollView!
@IBOutlet private var backgroundView: UIView!
@IBOutlet private var contentTextView: OEXPlaceholderTextView!
@IBOutlet private var titleTextField: LogistrationTextField!
@IBOutlet private var discussionQuestionSegmentedControl: UISegmentedControl!
@IBOutlet private var bodyTextViewHeightConstraint: NSLayoutConstraint!
@IBOutlet private var topicButton: UIButton!
@IBOutlet private var postButton: SpinnerButton!
@IBOutlet weak var contentTitleLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
private let loadController = LoadStateViewController()
private let courseID: String
fileprivate let topics = BackedStream<[DiscussionTopic]>()
private var selectedTopic: DiscussionTopic?
private var optionsViewController: MenuOptionsViewController?
weak var delegate: DiscussionNewPostViewControllerDelegate?
private let tapButton = UIButton()
var titleTextStyle: OEXTextStyle {
return OEXTextStyle(weight : .normal, size: .small, color: OEXStyles.shared().primaryXLightColor())
}
private var selectedThreadType: DiscussionThreadType = .Discussion {
didSet {
switch selectedThreadType {
case .Discussion:
self.contentTitleLabel.attributedText = NSAttributedString.joinInNaturalLayout(attributedStrings: [titleTextStyle.attributedString(withText: Strings.Dashboard.courseDiscussion), titleTextStyle.attributedString(withText: Strings.asteric)])
postButton.applyButtonStyle(style: OEXStyles.shared().filledPrimaryButtonStyle,withTitle: Strings.postDiscussion)
contentTextView.accessibilityLabel = Strings.Dashboard.courseDiscussion
case .Question:
self.contentTitleLabel.attributedText = NSAttributedString.joinInNaturalLayout(attributedStrings: [titleTextStyle.attributedString(withText: Strings.question), titleTextStyle.attributedString(withText: Strings.asteric)])
postButton.applyButtonStyle(style: OEXStyles.shared().filledPrimaryButtonStyle, withTitle: Strings.postQuestion)
contentTextView.accessibilityLabel = Strings.question
}
}
}
public init(environment: Environment, courseID: String, selectedTopic : DiscussionTopic?) {
self.environment = environment
self.courseID = courseID
super.init(nibName: "DiscussionNewPostViewController", bundle: nil)
let stream = environment.dataManager.courseDataManager.discussionManagerForCourseWithID(courseID: courseID).topics
topics.backWithStream(stream.map {
return DiscussionTopic.linearizeTopics(topics: $0)
}
)
self.selectedTopic = selectedTopic
}
private var firstSelectableTopic : DiscussionTopic? {
let selectablePredicate = { (topic : DiscussionTopic) -> Bool in
topic.isSelectable
}
guard let topics = self.topics.value, let selectableTopicIndex = topics.firstIndexMatching(selectablePredicate) else {
return nil
}
return topics[selectableTopicIndex]
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@IBAction func postTapped(sender: AnyObject) {
postButton.isEnabled = false
postButton.showProgress = true
// create new thread (post)
if let topic = selectedTopic, let topicID = topic.id {
let newThread = DiscussionNewThread(courseID: courseID, topicID: topicID, type: selectedThreadType , title: titleTextField.text ?? "", rawBody: contentTextView.text)
let apiRequest = DiscussionAPI.createNewThread(newThread: newThread)
environment.networkManager.taskForRequest(apiRequest) {[weak self] result in
self?.postButton.isEnabled = true
self?.postButton.showProgress = false
if let post = result.data {
self?.delegate?.newPostController(controller: self!, addedPost: post)
self?.dismiss(animated: true, completion: nil)
}
else {
DiscussionHelper.showErrorMessage(controller: self, error: result.error)
}
}
}
}
override public func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = Strings.post
let cancelItem = UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: nil)
cancelItem.oex_setAction { [weak self]() -> Void in
self?.dismiss(animated: true, completion: nil)
}
self.navigationItem.leftBarButtonItem = cancelItem
contentTitleLabel.isAccessibilityElement = false
titleLabel.isAccessibilityElement = false
titleLabel.attributedText = NSAttributedString.joinInNaturalLayout(attributedStrings: [titleTextStyle.attributedString(withText: Strings.title), titleTextStyle.attributedString(withText: Strings.asteric)])
contentTextView.textContainer.lineFragmentPadding = 0
contentTextView.applyStandardBorderStyle()
contentTextView.delegate = self
titleTextField.accessibilityLabel = Strings.title
view.backgroundColor = OEXStyles.shared().standardBackgroundColor()
configureSegmentControl()
titleTextField.defaultTextAttributes = OEXStyles.shared().textAreaBodyStyle.attributes.attributedKeyDictionary()
setTopicsButtonTitle()
let insets = OEXStyles.shared().standardTextViewInsets
topicButton.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: insets.left, bottom: 0, right: insets.right)
topicButton.accessibilityHint = Strings.accessibilityShowsDropdownHint
topicButton.applyBorderStyle(style: OEXStyles.shared().entryFieldBorderStyle)
topicButton.localizedHorizontalContentAlignment = .Leading
let dropdownLabel = UILabel()
dropdownLabel.attributedText = Icon.Dropdown.attributedTextWithStyle(style: titleTextStyle)
topicButton.addSubview(dropdownLabel)
dropdownLabel.snp.makeConstraints { make in
make.trailing.equalTo(topicButton).offset(-insets.right)
make.top.equalTo(topicButton).offset(topicButton.frame.size.height / 2.0 - 5.0)
}
topicButton.oex_addAction({ [weak self] (action : AnyObject!) -> Void in
self?.showTopicPicker()
}, for: UIControl.Event.touchUpInside)
postButton.isEnabled = false
titleTextField.oex_addAction({[weak self] _ in
self?.validatePostButton()
}, for: .editingChanged)
self.growingTextController.setupWithScrollView(scrollView: scrollView, textView: contentTextView, bottomView: postButton)
self.insetsController.setupInController(owner: self, scrollView: scrollView)
// Force setting it to call didSet which is only called out of initialization context
self.selectedThreadType = .Question
loadController.setupInController(controller: self, contentView: self.scrollView)
topics.listen(self, success : {[weak self]_ in
self?.loadedData()
}, failure : {[weak self] error in
self?.loadController.state = LoadState.failed(error: error)
})
backgroundView.addSubview(tapButton)
backgroundView.sendSubviewToBack(tapButton)
tapButton.backgroundColor = UIColor.clear
tapButton.frame = CGRect(x: 0, y: 0, width: backgroundView.frame.size.width, height: backgroundView.frame.size.height)
tapButton.isAccessibilityElement = false
tapButton.accessibilityLabel = Strings.accessibilityHideKeyboard
tapButton.oex_addAction({[weak self] (sender) in
self?.view.endEditing(true)
}, for: .touchUpInside)
setAccessibilityIdentifiers()
}
private func setAccessibilityIdentifiers() {
view.accessibilityIdentifier = "DiscussionNewPostViewController:view"
scrollView.accessibilityIdentifier = "DiscussionNewPostViewController:scroll-view"
backgroundView.accessibilityIdentifier = "DiscussionNewPostViewController:background-view"
contentTextView.accessibilityIdentifier = "DiscussionNewPostViewController:content-text-view"
titleTextField.accessibilityIdentifier = "DiscussionNewPostViewController:title-text-field"
discussionQuestionSegmentedControl.accessibilityIdentifier = "DiscussionNewPostViewController:segment-control"
topicButton.accessibilityIdentifier = "DiscussionNewPostViewController:topic-button"
postButton.accessibilityIdentifier = "DiscussionNewPostViewController:post-button"
contentTitleLabel.accessibilityIdentifier = "DiscussionNewPostViewController:content-title-label"
titleLabel.accessibilityIdentifier = "DiscussionNewPostViewController:title-label"
tapButton.accessibilityIdentifier = "DiscussionNewPostViewController:tap-button"
}
private func configureSegmentControl() {
discussionQuestionSegmentedControl.removeAllSegments()
let questionIcon = Icon.Question.attributedTextWithStyle(style: titleTextStyle)
let questionTitle = NSAttributedString.joinInNaturalLayout(attributedStrings: [questionIcon,
titleTextStyle.attributedString(withText: Strings.question)])
let discussionIcon = Icon.Comments.attributedTextWithStyle(style: titleTextStyle)
let discussionTitle = NSAttributedString.joinInNaturalLayout(attributedStrings: [discussionIcon,
titleTextStyle.attributedString(withText: Strings.discussion)])
let segmentOptions : [(title : NSAttributedString, value : DiscussionThreadType)] = [
(title : questionTitle, value : .Question),
(title : discussionTitle, value : .Discussion),
]
for i in 0..<segmentOptions.count {
discussionQuestionSegmentedControl.insertSegmentWithAttributedTitle(title: segmentOptions[i].title, index: i, animated: false)
discussionQuestionSegmentedControl.subviews[i].accessibilityLabel = segmentOptions[i].title.string
}
discussionQuestionSegmentedControl.oex_addAction({ [weak self] (control:AnyObject) -> Void in
if let segmentedControl = control as? UISegmentedControl {
let index = segmentedControl.selectedSegmentIndex
let threadType = segmentOptions[index].value
self?.selectedThreadType = threadType
self?.updateSelectedTabColor()
}
else {
assert(true, "Invalid Segment ID, Remove this segment index OR handle it in the ThreadType enum")
}
}, for: UIControl.Event.valueChanged)
discussionQuestionSegmentedControl.tintColor = OEXStyles.shared().primaryXLightColor()
discussionQuestionSegmentedControl.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: OEXStyles.shared().neutralWhite()], for: UIControl.State.selected)
discussionQuestionSegmentedControl.selectedSegmentIndex = 0
updateSelectedTabColor()
}
private func updateSelectedTabColor() {
// //UIsegmentControl don't Multiple tint color so updating tint color of subviews to match desired behaviour
let subViews:NSArray = discussionQuestionSegmentedControl.subviews as NSArray
for i in 0..<subViews.count {
if (subViews.object(at: i) as AnyObject).isSelected ?? false {
let view = subViews.object(at: i) as! UIView
view.tintColor = OEXStyles.shared().primaryBaseColor()
}
else {
let view = subViews.object(at: i) as! UIView
view.tintColor = OEXStyles.shared().primaryXLightColor()
}
}
}
override public func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.environment.analytics.trackDiscussionScreen(withName: AnalyticsScreenName.CreateTopicThread, courseId: self.courseID, value: selectedTopic?.name, threadId: nil, topicId: selectedTopic?.id, responseID: nil)
}
override public var shouldAutorotate: Bool {
return true
}
override public var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .allButUpsideDown
}
private func loadedData() {
loadController.state = topics.value?.count == 0 ? LoadState.empty(icon: .NoTopics, message : Strings.unableToLoadCourseContent) : .Loaded
if selectedTopic == nil {
selectedTopic = firstSelectableTopic
}
setTopicsButtonTitle()
}
private func setTopicsButtonTitle() {
if let topic = selectedTopic, let name = topic.name {
let title = Strings.topic(topic: name)
topicButton.setAttributedTitle(OEXTextStyle(weight : .normal, size: .small, color: OEXStyles.shared().primaryXLightColor()).attributedString(withText: title), for: .normal)
}
}
func showTopicPicker() {
if self.optionsViewController != nil {
return
}
view.endEditing(true)
self.optionsViewController = MenuOptionsViewController()
self.optionsViewController?.delegate = self
guard let courseTopics = topics.value else {
//Don't need to configure an empty state here because it's handled in viewDidLoad()
return
}
self.optionsViewController?.options = courseTopics.map {
return MenuOptionsViewController.MenuOption(depth : $0.depth, label : $0.name ?? "")
}
self.optionsViewController?.selectedOptionIndex = self.selectedTopicIndex()
self.view.addSubview(self.optionsViewController!.view)
self.optionsViewController!.view.snp.makeConstraints { make in
make.trailing.equalTo(self.topicButton)
make.leading.equalTo(self.topicButton)
make.top.equalTo(self.topicButton.snp.bottom).offset(-3)
make.bottom.equalTo(safeBottom)
}
self.optionsViewController?.view.alpha = 0.0
UIView.animate(withDuration: 0.3) {
self.optionsViewController?.view.alpha = 1.0
}
}
private func selectedTopicIndex() -> Int? {
guard let selected = selectedTopic else {
return 0
}
return self.topics.value?.firstIndexMatching {
return $0.id == selected.id
}
}
public func textViewDidChange(_ textView: UITextView) {
validatePostButton()
growingTextController.handleTextChange()
}
public func menuOptionsController(controller : MenuOptionsViewController, canSelectOptionAtIndex index : Int) -> Bool {
return self.topics.value?[index].isSelectable ?? false
}
private func validatePostButton() {
self.postButton.isEnabled = !(titleTextField.text ?? "").isEmpty && !contentTextView.text.isEmpty && self.selectedTopic != nil
}
func menuOptionsController(controller : MenuOptionsViewController, selectedOptionAtIndex index: Int) {
selectedTopic = self.topics.value?[index]
if let topic = selectedTopic, topic.id != nil {
setTopicsButtonTitle()
UIAccessibility.post(notification: UIAccessibility.Notification.layoutChanged, argument: titleTextField);
UIView.animate(withDuration: 0.3, animations: {
self.optionsViewController?.view.alpha = 0.0
}, completion: {[weak self](finished: Bool) in
self?.optionsViewController?.view.removeFromSuperview()
self?.optionsViewController = nil
})
}
}
public override func viewDidLayoutSubviews() {
self.insetsController.updateInsets()
growingTextController.scrollToVisible()
}
private func textFieldDidBeginEditing(textField: UITextField) {
tapButton.isAccessibilityElement = true
}
private func textFieldDidEndEditing(textField: UITextField) {
tapButton.isAccessibilityElement = false
}
public func textViewDidBeginEditing(_ textView: UITextView) {
tapButton.isAccessibilityElement = true
}
public func textViewDidEndEditing(_ textView: UITextView) {
tapButton.isAccessibilityElement = false
}
}
extension UISegmentedControl {
//UIsegmentControl didn't support attributedTitle by default
func insertSegmentWithAttributedTitle(title: NSAttributedString, index: NSInteger, animated: Bool) {
let segmentLabel = UILabel()
segmentLabel.backgroundColor = UIColor.clear
segmentLabel.textAlignment = .center
segmentLabel.attributedText = title
segmentLabel.sizeToFit()
self.insertSegment(with: segmentLabel.toImage(), at: 1, animated: false)
}
}
extension UILabel {
func toImage()-> UIImage? {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, false, 0)
self.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext();
return image;
}
}
// For use in testing only
extension DiscussionNewPostViewController {
public func t_topicsLoaded() -> OEXStream<[DiscussionTopic]> {
return topics
}
}
| apache-2.0 |
tutao/tutanota | app-ios/tutanota/Sources/GeneratedIpc/MobileFacade.swift | 1 | 648 | /* generated file, don't edit. */
import Foundation
/**
* Common operations used by mobile platforms.
*/
public protocol MobileFacade {
/**
* Android: Called when 'hardware' back key is pressed. Returns `true` if the web app consumed the event.
*/
func handleBackPress(
) async throws -> Bool
/**
* Android: called when the app becomes completely visible/hidden (not just covered by dialog).
*/
func visibilityChange(
_ visibility: Bool
) async throws -> Void
/**
* iOS: called when keyboard opens/closes/resizes. Passes the height of the keyboard.
*/
func keyboardSizeChanged(
_ newSize: Int
) async throws -> Void
}
| gpl-3.0 |
JakeLin/LoveFinder | LoveFinderTests/LoveFinderTests.swift | 4 | 905 | //
// LoveFinderTests.swift
// LoveFinderTests
//
// Created by Jake Lin on 25/08/2014.
// Copyright (c) 2014 rushjet. All rights reserved.
//
import UIKit
import XCTest
class LoveFinderTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
XCTAssert(true, "Pass")
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measureBlock() {
// Put the code you want to measure the time of here.
}
}
}
| mit |
glimpseio/ChannelZ | Sources/ChannelZ/Combinators.swift | 1 | 64865 | //
// Combinators.swift
// ChannelZ
//
// Created by Marc Prud'hommeaux on 4/5/16.
// Copyright © 2010-2020 glimpse.io. All rights reserved.
//
// Swift 4 TODO: Variadic Generics: https://github.com/apple/swift/blob/master/docs/GenericsManifesto.md#variadic-generics
/// One of a set number of options; simulates a union of arbitrarity arity
public protocol ChooseNType {
/// Returns the number of choices
var arity: Int { get }
/// The first type in thie choice; also the primary type, in that it will be the subject of `firstMap`
associatedtype T1
var v1: T1? { get set }
}
public extension ChooseNType {
/// Similar to `flatMap`, except it will call the function when the element of this
/// type is the T1 type, and null if it is any other type (T2, T3, ...)
@inlinable func firstMap<U>(_ f: (T1) throws -> U?) rethrows -> U? {
if let value = self.v1 {
return try f(value)
} else {
return nil
}
}
}
/// One of at least 2 options
public protocol Choose2Type : ChooseNType {
associatedtype T2
var v2: T2? { get set }
}
/// An error that indicates that multiple errors occured when decoding the type;
/// Each error should correspond to one of the choices for this type.
public struct ChoiceDecodingError<T: ChooseNType> : Error {
public let errors: [Error]
public init(errors: [Error]) {
self.errors = errors
}
}
/// One of exactly 2 options
public enum Choose2<T1, T2>: Choose2Type {
public var arity: Int { return 2 }
/// First of 2
case v1(T1)
/// Second of 2
case v2(T2)
@inlinable public init(t1: T1) { self = .v1(t1) }
@inlinable public init(_ t1: T1) { self = .v1(t1) }
@inlinable public init(t2: T2) { self = .v2(t2) }
@inlinable public init(_ t2: T2) { self = .v2(t2) }
@inlinable public var first: T1? { if case .v1(let x) = self { return x } else { return nil } }
@inlinable public var v1: T1? {
get { if case .v1(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v1(x) } }
}
@inlinable public var v2: T2? {
get { if case .v2(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v2(x) } }
}
}
public extension Choose2 where T1 == T2 {
/// When a ChooseN type wraps the same value types, returns the single value
@inlinable var value: T1 {
switch self {
case .v1(let x): return x
case .v2(let x): return x
}
}
}
extension Choose2 : Encodable where T1 : Encodable, T2 : Encodable {
@inlinable public func encode(to encoder: Encoder) throws {
switch self {
case .v1(let x): try x.encode(to: encoder)
case .v2(let x): try x.encode(to: encoder)
}
}
}
extension Choose2 : Decodable where T1 : Decodable, T2 : Decodable {
@inlinable public init(from decoder: Decoder) throws {
var errors: [Error] = []
do { self = try .v1(T1(from: decoder)); return } catch { errors.append(error) }
do { self = try .v2(T2(from: decoder)); return } catch { errors.append(error) }
throw ChoiceDecodingError<Choose2>(errors: errors)
}
}
extension Choose2 : Equatable where T1 : Equatable, T2 : Equatable { }
extension Choose2 : Hashable where T1 : Hashable, T2 : Hashable { }
/// One of at least 3 options
public protocol Choose3Type : Choose2Type {
associatedtype T3
var v3: T3? { get set }
}
/// One of exactly 3 options
public enum Choose3<T1, T2, T3>: Choose3Type {
@inlinable public var arity: Int { return 3 }
/// First of 3
case v1(T1)
/// Second of 3
case v2(T2)
/// Third of 3
case v3(T3)
@inlinable public init(t1: T1) { self = .v1(t1) }
@inlinable public init(_ t1: T1) { self = .v1(t1) }
@inlinable public init(t2: T2) { self = .v2(t2) }
@inlinable public init(_ t2: T2) { self = .v2(t2) }
@inlinable public init(t3: T3) { self = .v3(t3) }
@inlinable public init(_ t3: T3) { self = .v3(t3) }
@inlinable public var first: T1? { if case .v1(let x) = self { return x } else { return nil } }
@inlinable public var v1: T1? {
get { if case .v1(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v1(x) } }
}
@inlinable public var v2: T2? {
get { if case .v2(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v2(x) } }
}
@inlinable public var v3: T3? {
get { if case .v3(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v3(x) } }
}
/// Split the tuple into nested Choose2 instances
@inlinable public func split() -> Choose2<Choose2<T1, T2>, T3> {
switch self {
case .v1(let v): return .v1(.v1(v))
case .v2(let v): return .v1(.v2(v))
case .v3(let v): return .v2(v)
}
}
}
public extension Choose3 where T1 == T2, T2 == T3 {
/// When a ChooseN type wraps the same value types, returns the single value
@inlinable var value: T1 {
switch self {
case .v1(let x): return x
case .v2(let x): return x
case .v3(let x): return x
}
}
}
extension Choose3 : Encodable where T1 : Encodable, T2 : Encodable, T3 : Encodable {
@inlinable public func encode(to encoder: Encoder) throws {
switch self {
case .v1(let x): try x.encode(to: encoder)
case .v2(let x): try x.encode(to: encoder)
case .v3(let x): try x.encode(to: encoder)
}
}
}
extension Choose3 : Decodable where T1 : Decodable, T2 : Decodable, T3 : Decodable {
@inlinable public init(from decoder: Decoder) throws {
var errors: [Error] = []
do { self = try .v1(T1(from: decoder)); return } catch { errors.append(error) }
do { self = try .v2(T2(from: decoder)); return } catch { errors.append(error) }
do { self = try .v3(T3(from: decoder)); return } catch { errors.append(error) }
throw ChoiceDecodingError<Choose3>(errors: errors)
}
}
extension Choose3 : Equatable where T1 : Equatable, T2 : Equatable, T3 : Equatable { }
extension Choose3 : Hashable where T1 : Hashable, T2 : Hashable, T3 : Hashable { }
/// One of at least 4 options
public protocol Choose4Type : Choose3Type {
associatedtype T4
var v4: T4? { get set }
}
/// One of exactly 4 options
public enum Choose4<T1, T2, T3, T4>: Choose4Type {
@inlinable public var arity: Int { return 4 }
/// First of 4
case v1(T1)
/// Second of 4
case v2(T2)
/// Third of 4
case v3(T3)
/// Fourth of 4
case v4(T4)
@inlinable public init(t1: T1) { self = .v1(t1) }
@inlinable public init(_ t1: T1) { self = .v1(t1) }
@inlinable public init(t2: T2) { self = .v2(t2) }
@inlinable public init(_ t2: T2) { self = .v2(t2) }
@inlinable public init(t3: T3) { self = .v3(t3) }
@inlinable public init(_ t3: T3) { self = .v3(t3) }
@inlinable public init(t4: T4) { self = .v4(t4) }
@inlinable public init(_ t4: T4) { self = .v4(t4) }
@inlinable public var first: T1? { if case .v1(let x) = self { return x } else { return nil } }
@inlinable public var v1: T1? {
get { if case .v1(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v1(x) } }
}
@inlinable public var v2: T2? {
get { if case .v2(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v2(x) } }
}
@inlinable public var v3: T3? {
get { if case .v3(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v3(x) } }
}
@inlinable public var v4: T4? {
get { if case .v4(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v4(x) } }
}
/// Split the tuple into nested Choose2 instances
@inlinable public func split() -> Choose2<Choose2<Choose2<T1, T2>, T3>, T4> {
switch self {
case .v1(let v): return .v1(.v1(.v1(v)))
case .v2(let v): return .v1(.v1(.v2(v)))
case .v3(let v): return .v1(.v2(v))
case .v4(let v): return .v2(v)
}
}
}
public extension Choose4 where T1 == T2, T2 == T3, T3 == T4 {
/// When a ChooseN type wraps the same value types, returns the single value
@inlinable var value: T1 {
switch self {
case .v1(let x): return x
case .v2(let x): return x
case .v3(let x): return x
case .v4(let x): return x
}
}
}
extension Choose4 : Encodable where T1 : Encodable, T2 : Encodable, T3 : Encodable, T4 : Encodable {
@inlinable public func encode(to encoder: Encoder) throws {
switch self {
case .v1(let x): try x.encode(to: encoder)
case .v2(let x): try x.encode(to: encoder)
case .v3(let x): try x.encode(to: encoder)
case .v4(let x): try x.encode(to: encoder)
}
}
}
extension Choose4 : Decodable where T1 : Decodable, T2 : Decodable, T3 : Decodable, T4 : Decodable {
@inlinable public init(from decoder: Decoder) throws {
var errors: [Error] = []
do { self = try .v1(T1(from: decoder)); return } catch { errors.append(error) }
do { self = try .v2(T2(from: decoder)); return } catch { errors.append(error) }
do { self = try .v3(T3(from: decoder)); return } catch { errors.append(error) }
do { self = try .v4(T4(from: decoder)); return } catch { errors.append(error) }
throw ChoiceDecodingError<Choose4>(errors: errors)
}
}
extension Choose4 : Equatable where T1 : Equatable, T2 : Equatable, T3 : Equatable, T4 : Equatable { }
extension Choose4 : Hashable where T1 : Hashable, T2 : Hashable, T3 : Hashable, T4 : Hashable { }
/// One of at least 5 options
public protocol Choose5Type : Choose4Type {
associatedtype T5
var v5: T5? { get set }
}
/// One of exactly 5 options
public enum Choose5<T1, T2, T3, T4, T5>: Choose5Type {
@inlinable public var arity: Int { return 5 }
/// First of 5
case v1(T1)
/// Second of 5
case v2(T2)
/// Third of 5
case v3(T3)
/// Fourth of 5
case v4(T4)
/// Fifth of 5
case v5(T5)
@inlinable public init(t1: T1) { self = .v1(t1) }
@inlinable public init(_ t1: T1) { self = .v1(t1) }
@inlinable public init(t2: T2) { self = .v2(t2) }
@inlinable public init(_ t2: T2) { self = .v2(t2) }
@inlinable public init(t3: T3) { self = .v3(t3) }
@inlinable public init(_ t3: T3) { self = .v3(t3) }
@inlinable public init(t4: T4) { self = .v4(t4) }
@inlinable public init(_ t4: T4) { self = .v4(t4) }
@inlinable public init(t5: T5) { self = .v5(t5) }
@inlinable public init(_ t5: T5) { self = .v5(t5) }
@inlinable public var first: T1? { if case .v1(let x) = self { return x } else { return nil } }
@inlinable public var v1: T1? {
get { if case .v1(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v1(x) } }
}
@inlinable public var v2: T2? {
get { if case .v2(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v2(x) } }
}
@inlinable public var v3: T3? {
get { if case .v3(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v3(x) } }
}
@inlinable public var v4: T4? {
get { if case .v4(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v4(x) } }
}
@inlinable public var v5: T5? {
get { if case .v5(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v5(x) } }
}
/// Split the tuple into nested Choose2 instances
@inlinable public func split() -> Choose2<Choose2<Choose2<Choose2<T1, T2>, T3>, T4>, T5> {
switch self {
case .v1(let v): return .v1(.v1(.v1(.v1(v))))
case .v2(let v): return .v1(.v1(.v1(.v2(v))))
case .v3(let v): return .v1(.v1(.v2(v)))
case .v4(let v): return .v1(.v2(v))
case .v5(let v): return .v2(v)
}
}
}
public extension Choose5 where T1 == T2, T2 == T3, T3 == T4, T4 == T5 {
/// When a ChooseN type wraps the same value types, returns the single value
@inlinable var value: T1 {
switch self {
case .v1(let x): return x
case .v2(let x): return x
case .v3(let x): return x
case .v4(let x): return x
case .v5(let x): return x
}
}
}
extension Choose5 : Encodable where T1 : Encodable, T2 : Encodable, T3 : Encodable, T4 : Encodable, T5 : Encodable {
@inlinable public func encode(to encoder: Encoder) throws {
switch self {
case .v1(let x): try x.encode(to: encoder)
case .v2(let x): try x.encode(to: encoder)
case .v3(let x): try x.encode(to: encoder)
case .v4(let x): try x.encode(to: encoder)
case .v5(let x): try x.encode(to: encoder)
}
}
}
extension Choose5 : Decodable where T1 : Decodable, T2 : Decodable, T3 : Decodable, T4 : Decodable, T5 : Decodable {
@inlinable public init(from decoder: Decoder) throws {
var errors: [Error] = []
do { self = try .v1(T1(from: decoder)); return } catch { errors.append(error) }
do { self = try .v2(T2(from: decoder)); return } catch { errors.append(error) }
do { self = try .v3(T3(from: decoder)); return } catch { errors.append(error) }
do { self = try .v4(T4(from: decoder)); return } catch { errors.append(error) }
do { self = try .v5(T5(from: decoder)); return } catch { errors.append(error) }
throw ChoiceDecodingError<Choose5>(errors: errors)
}
}
extension Choose5 : Equatable where T1 : Equatable, T2 : Equatable, T3 : Equatable, T4 : Equatable, T5 : Equatable { }
extension Choose5 : Hashable where T1 : Hashable, T2 : Hashable, T3 : Hashable, T4 : Hashable, T5 : Hashable { }
/// One of at least 6 options
public protocol Choose6Type : Choose5Type {
associatedtype T6
var v6: T6? { get set }
}
/// One of exactly 6 options
public enum Choose6<T1, T2, T3, T4, T5, T6>: Choose6Type {
@inlinable public var arity: Int { return 6 }
/// First of 6
case v1(T1)
/// Second of 6
case v2(T2)
/// Third of 6
case v3(T3)
/// Fourth of 6
case v4(T4)
/// Fifth of 6
case v5(T5)
/// Sixth of 6
case v6(T6)
@inlinable public init(t1: T1) { self = .v1(t1) }
@inlinable public init(_ t1: T1) { self = .v1(t1) }
@inlinable public init(t2: T2) { self = .v2(t2) }
@inlinable public init(_ t2: T2) { self = .v2(t2) }
@inlinable public init(t3: T3) { self = .v3(t3) }
@inlinable public init(_ t3: T3) { self = .v3(t3) }
@inlinable public init(t4: T4) { self = .v4(t4) }
@inlinable public init(_ t4: T4) { self = .v4(t4) }
@inlinable public init(t5: T5) { self = .v5(t5) }
@inlinable public init(_ t5: T5) { self = .v5(t5) }
@inlinable public init(t6: T6) { self = .v6(t6) }
@inlinable public init(_ t6: T6) { self = .v6(t6) }
@inlinable public var first: T1? { if case .v1(let x) = self { return x } else { return nil } }
@inlinable public var v1: T1? {
get { if case .v1(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v1(x) } }
}
@inlinable public var v2: T2? {
get { if case .v2(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v2(x) } }
}
@inlinable public var v3: T3? {
get { if case .v3(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v3(x) } }
}
@inlinable public var v4: T4? {
get { if case .v4(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v4(x) } }
}
@inlinable public var v5: T5? {
get { if case .v5(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v5(x) } }
}
@inlinable public var v6: T6? {
get { if case .v6(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v6(x) } }
}
/// Split the tuple into nested Choose2 instances
@inlinable public func split() -> Choose2<Choose2<Choose2<Choose2<Choose2<T1, T2>, T3>, T4>, T5>, T6> {
switch self {
case .v1(let v): return .v1(.v1(.v1(.v1(.v1(v)))))
case .v2(let v): return .v1(.v1(.v1(.v1(.v2(v)))))
case .v3(let v): return .v1(.v1(.v1(.v2(v))))
case .v4(let v): return .v1(.v1(.v2(v)))
case .v5(let v): return .v1(.v2(v))
case .v6(let v): return .v2(v)
}
}
}
public extension Choose6 where T1 == T2, T2 == T3, T3 == T4, T4 == T5, T5 == T6 {
/// When a ChooseN type wraps the same value types, returns the single value
var value: T1 {
switch self {
case .v1(let x): return x
case .v2(let x): return x
case .v3(let x): return x
case .v4(let x): return x
case .v5(let x): return x
case .v6(let x): return x
}
}
}
extension Choose6 : Encodable where T1 : Encodable, T2 : Encodable, T3 : Encodable, T4 : Encodable, T5 : Encodable, T6 : Encodable {
@inlinable public func encode(to encoder: Encoder) throws {
switch self {
case .v1(let x): try x.encode(to: encoder)
case .v2(let x): try x.encode(to: encoder)
case .v3(let x): try x.encode(to: encoder)
case .v4(let x): try x.encode(to: encoder)
case .v5(let x): try x.encode(to: encoder)
case .v6(let x): try x.encode(to: encoder)
}
}
}
extension Choose6 : Decodable where T1 : Decodable, T2 : Decodable, T3 : Decodable, T4 : Decodable, T5 : Decodable, T6 : Decodable {
@inlinable public init(from decoder: Decoder) throws {
var errors: [Error] = []
do { self = try .v1(T1(from: decoder)); return } catch { errors.append(error) }
do { self = try .v2(T2(from: decoder)); return } catch { errors.append(error) }
do { self = try .v3(T3(from: decoder)); return } catch { errors.append(error) }
do { self = try .v4(T4(from: decoder)); return } catch { errors.append(error) }
do { self = try .v5(T5(from: decoder)); return } catch { errors.append(error) }
do { self = try .v6(T6(from: decoder)); return } catch { errors.append(error) }
throw ChoiceDecodingError<Choose6>(errors: errors)
}
}
extension Choose6 : Equatable where T1 : Equatable, T2 : Equatable, T3 : Equatable, T4 : Equatable, T5 : Equatable, T6 : Equatable { }
extension Choose6 : Hashable where T1 : Hashable, T2 : Hashable, T3 : Hashable, T4 : Hashable, T5 : Hashable, T6 : Hashable { }
/// One of at least 7 options
public protocol Choose7Type : Choose6Type {
associatedtype T7
var v7: T7? { get set }
}
/// One of exactly 7 options
public enum Choose7<T1, T2, T3, T4, T5, T6, T7>: Choose7Type {
@inlinable public var arity: Int { return 7 }
/// First of 7
case v1(T1)
/// Second of 7
case v2(T2)
/// Third of 7
case v3(T3)
/// Fourth of 7
case v4(T4)
/// Fifth of 7
case v5(T5)
/// Sixth of 7
case v6(T6)
/// Seventh of 7
case v7(T7)
@inlinable public init(t1: T1) { self = .v1(t1) }
@inlinable public init(_ t1: T1) { self = .v1(t1) }
@inlinable public init(t2: T2) { self = .v2(t2) }
@inlinable public init(_ t2: T2) { self = .v2(t2) }
@inlinable public init(t3: T3) { self = .v3(t3) }
@inlinable public init(_ t3: T3) { self = .v3(t3) }
@inlinable public init(t4: T4) { self = .v4(t4) }
@inlinable public init(_ t4: T4) { self = .v4(t4) }
@inlinable public init(t5: T5) { self = .v5(t5) }
@inlinable public init(_ t5: T5) { self = .v5(t5) }
@inlinable public init(t6: T6) { self = .v6(t6) }
@inlinable public init(_ t6: T6) { self = .v6(t6) }
@inlinable public init(t7: T7) { self = .v7(t7) }
@inlinable public init(_ t7: T7) { self = .v7(t7) }
@inlinable public var first: T1? { if case .v1(let x) = self { return x } else { return nil } }
@inlinable public var v1: T1? {
get { if case .v1(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v1(x) } }
}
@inlinable public var v2: T2? {
get { if case .v2(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v2(x) } }
}
@inlinable public var v3: T3? {
get { if case .v3(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v3(x) } }
}
@inlinable public var v4: T4? {
get { if case .v4(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v4(x) } }
}
@inlinable public var v5: T5? {
get { if case .v5(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v5(x) } }
}
@inlinable public var v6: T6? {
get { if case .v6(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v6(x) } }
}
@inlinable public var v7: T7? {
get { if case .v7(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v7(x) } }
}
/// Split the tuple into nested Choose2 instances
@inlinable public func split() -> Choose2<Choose2<Choose2<Choose2<Choose2<Choose2<T1, T2>, T3>, T4>, T5>, T6>, T7> {
switch self {
case .v1(let v): return .v1(.v1(.v1(.v1(.v1(.v1(v))))))
case .v2(let v): return .v1(.v1(.v1(.v1(.v1(.v2(v))))))
case .v3(let v): return .v1(.v1(.v1(.v1(.v2(v)))))
case .v4(let v): return .v1(.v1(.v1(.v2(v))))
case .v5(let v): return .v1(.v1(.v2(v)))
case .v6(let v): return .v1(.v2(v))
case .v7(let v): return .v2(v)
}
}
}
public extension Choose7 where T1 == T2, T2 == T3, T3 == T4, T4 == T5, T5 == T6, T6 == T7 {
/// When a ChooseN type wraps the same value types, returns the single value
@inlinable var value: T1 {
switch self {
case .v1(let x): return x
case .v2(let x): return x
case .v3(let x): return x
case .v4(let x): return x
case .v5(let x): return x
case .v6(let x): return x
case .v7(let x): return x
}
}
}
extension Choose7 : Encodable where T1 : Encodable, T2 : Encodable, T3 : Encodable, T4 : Encodable, T5 : Encodable, T6 : Encodable, T7 : Encodable {
@inlinable public func encode(to encoder: Encoder) throws {
switch self {
case .v1(let x): try x.encode(to: encoder)
case .v2(let x): try x.encode(to: encoder)
case .v3(let x): try x.encode(to: encoder)
case .v4(let x): try x.encode(to: encoder)
case .v5(let x): try x.encode(to: encoder)
case .v6(let x): try x.encode(to: encoder)
case .v7(let x): try x.encode(to: encoder)
}
}
}
extension Choose7 : Decodable where T1 : Decodable, T2 : Decodable, T3 : Decodable, T4 : Decodable, T5 : Decodable, T6 : Decodable, T7 : Decodable {
@inlinable public init(from decoder: Decoder) throws {
var errors: [Error] = []
do { self = try .v1(T1(from: decoder)); return } catch { errors.append(error) }
do { self = try .v2(T2(from: decoder)); return } catch { errors.append(error) }
do { self = try .v3(T3(from: decoder)); return } catch { errors.append(error) }
do { self = try .v4(T4(from: decoder)); return } catch { errors.append(error) }
do { self = try .v5(T5(from: decoder)); return } catch { errors.append(error) }
do { self = try .v6(T6(from: decoder)); return } catch { errors.append(error) }
do { self = try .v7(T7(from: decoder)); return } catch { errors.append(error) }
throw ChoiceDecodingError<Choose7>(errors: errors)
}
}
extension Choose7 : Equatable where T1 : Equatable, T2 : Equatable, T3 : Equatable, T4 : Equatable, T5 : Equatable, T6 : Equatable, T7 : Equatable { }
extension Choose7 : Hashable where T1 : Hashable, T2 : Hashable, T3 : Hashable, T4 : Hashable, T5 : Hashable, T6 : Hashable, T7 : Hashable { }
/// One of at least 8 options
public protocol Choose8Type : Choose7Type {
associatedtype T8
var v8: T8? { get set }
}
/// One of exactly 8 options
public enum Choose8<T1, T2, T3, T4, T5, T6, T7, T8>: Choose8Type {
@inlinable public var arity: Int { return 8 }
/// First of 8
case v1(T1)
/// Second of 8
case v2(T2)
/// Third of 8
case v3(T3)
/// Fourth of 8
case v4(T4)
/// Fifth of 8
case v5(T5)
/// Sixth of 8
case v6(T6)
/// Seventh of 8
case v7(T7)
/// Eighth of 8
case v8(T8)
@inlinable public init(t1: T1) { self = .v1(t1) }
@inlinable public init(_ t1: T1) { self = .v1(t1) }
@inlinable public init(t2: T2) { self = .v2(t2) }
@inlinable public init(_ t2: T2) { self = .v2(t2) }
@inlinable public init(t3: T3) { self = .v3(t3) }
@inlinable public init(_ t3: T3) { self = .v3(t3) }
@inlinable public init(t4: T4) { self = .v4(t4) }
@inlinable public init(_ t4: T4) { self = .v4(t4) }
@inlinable public init(t5: T5) { self = .v5(t5) }
@inlinable public init(_ t5: T5) { self = .v5(t5) }
@inlinable public init(t6: T6) { self = .v6(t6) }
@inlinable public init(_ t6: T6) { self = .v6(t6) }
@inlinable public init(t7: T7) { self = .v7(t7) }
@inlinable public init(_ t7: T7) { self = .v7(t7) }
@inlinable public init(t8: T8) { self = .v8(t8) }
@inlinable public init(_ t8: T8) { self = .v8(t8) }
@inlinable public var first: T1? { if case .v1(let x) = self { return x } else { return nil } }
@inlinable public var v1: T1? {
get { if case .v1(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v1(x) } }
}
@inlinable public var v2: T2? {
get { if case .v2(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v2(x) } }
}
@inlinable public var v3: T3? {
get { if case .v3(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v3(x) } }
}
@inlinable public var v4: T4? {
get { if case .v4(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v4(x) } }
}
@inlinable public var v5: T5? {
get { if case .v5(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v5(x) } }
}
@inlinable public var v6: T6? {
get { if case .v6(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v6(x) } }
}
@inlinable public var v7: T7? {
get { if case .v7(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v7(x) } }
}
@inlinable public var v8: T8? {
get { if case .v8(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v8(x) } }
}
/// Split the tuple into nested Choose2 instances
@inlinable public func split() -> Choose2<Choose2<Choose2<Choose2<Choose2<Choose2<Choose2<T1, T2>, T3>, T4>, T5>, T6>, T7>, T8> {
switch self {
case .v1(let v): return .v1(.v1(.v1(.v1(.v1(.v1(.v1(v)))))))
case .v2(let v): return .v1(.v1(.v1(.v1(.v1(.v1(.v2(v)))))))
case .v3(let v): return .v1(.v1(.v1(.v1(.v1(.v2(v))))))
case .v4(let v): return .v1(.v1(.v1(.v1(.v2(v)))))
case .v5(let v): return .v1(.v1(.v1(.v2(v))))
case .v6(let v): return .v1(.v1(.v2(v)))
case .v7(let v): return .v1(.v2(v))
case .v8(let v): return .v2(v)
}
}
}
public extension Choose8 where T1 == T2, T2 == T3, T3 == T4, T4 == T5, T5 == T6, T6 == T7, T7 == T8 {
/// When a ChooseN type wraps the same value types, returns the single value
@inlinable var value: T1 {
switch self {
case .v1(let x): return x
case .v2(let x): return x
case .v3(let x): return x
case .v4(let x): return x
case .v5(let x): return x
case .v6(let x): return x
case .v7(let x): return x
case .v8(let x): return x
}
}
}
extension Choose8 : Encodable where T1 : Encodable, T2 : Encodable, T3 : Encodable, T4 : Encodable, T5 : Encodable, T6 : Encodable, T7 : Encodable, T8 : Encodable {
@inlinable public func encode(to encoder: Encoder) throws {
switch self {
case .v1(let x): try x.encode(to: encoder)
case .v2(let x): try x.encode(to: encoder)
case .v3(let x): try x.encode(to: encoder)
case .v4(let x): try x.encode(to: encoder)
case .v5(let x): try x.encode(to: encoder)
case .v6(let x): try x.encode(to: encoder)
case .v7(let x): try x.encode(to: encoder)
case .v8(let x): try x.encode(to: encoder)
}
}
}
extension Choose8 : Decodable where T1 : Decodable, T2 : Decodable, T3 : Decodable, T4 : Decodable, T5 : Decodable, T6 : Decodable, T7 : Decodable, T8 : Decodable {
@inlinable public init(from decoder: Decoder) throws {
var errors: [Error] = []
do { self = try .v1(T1(from: decoder)); return } catch { errors.append(error) }
do { self = try .v2(T2(from: decoder)); return } catch { errors.append(error) }
do { self = try .v3(T3(from: decoder)); return } catch { errors.append(error) }
do { self = try .v4(T4(from: decoder)); return } catch { errors.append(error) }
do { self = try .v5(T5(from: decoder)); return } catch { errors.append(error) }
do { self = try .v6(T6(from: decoder)); return } catch { errors.append(error) }
do { self = try .v7(T7(from: decoder)); return } catch { errors.append(error) }
do { self = try .v8(T8(from: decoder)); return } catch { errors.append(error) }
throw ChoiceDecodingError<Choose8>(errors: errors)
}
}
extension Choose8 : Equatable where T1 : Equatable, T2 : Equatable, T3 : Equatable, T4 : Equatable, T5 : Equatable, T6 : Equatable, T7 : Equatable, T8 : Equatable { }
extension Choose8 : Hashable where T1 : Hashable, T2 : Hashable, T3 : Hashable, T4 : Hashable, T5 : Hashable, T6 : Hashable, T7 : Hashable, T8 : Hashable { }
/// One of at least 9 options
public protocol Choose9Type : Choose8Type {
associatedtype T9
var v9: T9? { get set }
}
/// One of exactly 9 options
public enum Choose9<T1, T2, T3, T4, T5, T6, T7, T8, T9>: Choose9Type {
@inlinable public var arity: Int { return 9 }
/// First of 9
case v1(T1)
/// Second of 9
case v2(T2)
/// Third of 9
case v3(T3)
/// Fourth of 9
case v4(T4)
/// Fifth of 9
case v5(T5)
/// Sixth of 9
case v6(T6)
/// Seventh of 9
case v7(T7)
/// Eighth of 9
case v8(T8)
/// Ninth of 9
case v9(T9)
@inlinable public init(t1: T1) { self = .v1(t1) }
@inlinable public init(_ t1: T1) { self = .v1(t1) }
@inlinable public init(t2: T2) { self = .v2(t2) }
@inlinable public init(_ t2: T2) { self = .v2(t2) }
@inlinable public init(t3: T3) { self = .v3(t3) }
@inlinable public init(_ t3: T3) { self = .v3(t3) }
@inlinable public init(t4: T4) { self = .v4(t4) }
@inlinable public init(_ t4: T4) { self = .v4(t4) }
@inlinable public init(t5: T5) { self = .v5(t5) }
@inlinable public init(_ t5: T5) { self = .v5(t5) }
@inlinable public init(t6: T6) { self = .v6(t6) }
@inlinable public init(_ t6: T6) { self = .v6(t6) }
@inlinable public init(t7: T7) { self = .v7(t7) }
@inlinable public init(_ t7: T7) { self = .v7(t7) }
@inlinable public init(t8: T8) { self = .v8(t8) }
@inlinable public init(_ t8: T8) { self = .v8(t8) }
@inlinable public init(t9: T9) { self = .v9(t9) }
@inlinable public init(_ t9: T9) { self = .v9(t9) }
@inlinable public var first: T1? { if case .v1(let x) = self { return x } else { return nil } }
@inlinable public var v1: T1? {
get { if case .v1(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v1(x) } }
}
@inlinable public var v2: T2? {
get { if case .v2(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v2(x) } }
}
@inlinable public var v3: T3? {
get { if case .v3(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v3(x) } }
}
@inlinable public var v4: T4? {
get { if case .v4(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v4(x) } }
}
@inlinable public var v5: T5? {
get { if case .v5(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v5(x) } }
}
@inlinable public var v6: T6? {
get { if case .v6(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v6(x) } }
}
@inlinable public var v7: T7? {
get { if case .v7(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v7(x) } }
}
@inlinable public var v8: T8? {
get { if case .v8(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v8(x) } }
}
@inlinable public var v9: T9? {
get { if case .v9(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v9(x) } }
}
/// Split the tuple into nested Choose2 instances
@inlinable public func split() -> Choose2<Choose2<Choose2<Choose2<Choose2<Choose2<Choose2<Choose2<T1, T2>, T3>, T4>, T5>, T6>, T7>, T8>, T9> {
switch self {
case .v1(let v): return .v1(.v1(.v1(.v1(.v1(.v1(.v1(.v1(v))))))))
case .v2(let v): return .v1(.v1(.v1(.v1(.v1(.v1(.v1(.v2(v))))))))
case .v3(let v): return .v1(.v1(.v1(.v1(.v1(.v1(.v2(v)))))))
case .v4(let v): return .v1(.v1(.v1(.v1(.v1(.v2(v))))))
case .v5(let v): return .v1(.v1(.v1(.v1(.v2(v)))))
case .v6(let v): return .v1(.v1(.v1(.v2(v))))
case .v7(let v): return .v1(.v1(.v2(v)))
case .v8(let v): return .v1(.v2(v))
case .v9(let v): return .v2(v)
}
}
}
public extension Choose9 where T1 == T2, T2 == T3, T3 == T4, T4 == T5, T5 == T6, T6 == T7, T7 == T8, T8 == T9 {
/// When a ChooseN type wraps the same value types, returns the single value
@inlinable var value: T1 {
switch self {
case .v1(let x): return x
case .v2(let x): return x
case .v3(let x): return x
case .v4(let x): return x
case .v5(let x): return x
case .v6(let x): return x
case .v7(let x): return x
case .v8(let x): return x
case .v9(let x): return x
}
}
}
extension Choose9 : Encodable where T1 : Encodable, T2 : Encodable, T3 : Encodable, T4 : Encodable, T5 : Encodable, T6 : Encodable, T7 : Encodable, T8 : Encodable, T9 : Encodable {
@inlinable public func encode(to encoder: Encoder) throws {
switch self {
case .v1(let x): try x.encode(to: encoder)
case .v2(let x): try x.encode(to: encoder)
case .v3(let x): try x.encode(to: encoder)
case .v4(let x): try x.encode(to: encoder)
case .v5(let x): try x.encode(to: encoder)
case .v6(let x): try x.encode(to: encoder)
case .v7(let x): try x.encode(to: encoder)
case .v8(let x): try x.encode(to: encoder)
case .v9(let x): try x.encode(to: encoder)
}
}
}
extension Choose9 : Decodable where T1 : Decodable, T2 : Decodable, T3 : Decodable, T4 : Decodable, T5 : Decodable, T6 : Decodable, T7 : Decodable, T8 : Decodable, T9 : Decodable {
@inlinable public init(from decoder: Decoder) throws {
var errors: [Error] = []
do { self = try .v1(T1(from: decoder)); return } catch { errors.append(error) }
do { self = try .v2(T2(from: decoder)); return } catch { errors.append(error) }
do { self = try .v3(T3(from: decoder)); return } catch { errors.append(error) }
do { self = try .v4(T4(from: decoder)); return } catch { errors.append(error) }
do { self = try .v5(T5(from: decoder)); return } catch { errors.append(error) }
do { self = try .v6(T6(from: decoder)); return } catch { errors.append(error) }
do { self = try .v7(T7(from: decoder)); return } catch { errors.append(error) }
do { self = try .v8(T8(from: decoder)); return } catch { errors.append(error) }
do { self = try .v9(T9(from: decoder)); return } catch { errors.append(error) }
throw ChoiceDecodingError<Choose9>(errors: errors)
}
}
extension Choose9 : Equatable where T1 : Equatable, T2 : Equatable, T3 : Equatable, T4 : Equatable, T5 : Equatable, T6 : Equatable, T7 : Equatable, T8 : Equatable, T9 : Equatable { }
extension Choose9 : Hashable where T1 : Hashable, T2 : Hashable, T3 : Hashable, T4 : Hashable, T5 : Hashable, T6 : Hashable, T7 : Hashable, T8 : Hashable, T9 : Hashable { }
/// One of at least 10 options
public protocol Choose10Type : Choose9Type {
associatedtype T10
var v10: T10? { get set }
}
/// One of exactly 10 options
public enum Choose10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>: Choose10Type {
@inlinable public var arity: Int { return 10 }
/// First of 10
case v1(T1)
/// Second of 10
case v2(T2)
/// Third of 10
case v3(T3)
/// Fourth of 10
case v4(T4)
/// Fifth of 10
case v5(T5)
/// Sixth of 10
case v6(T6)
/// Seventh of 10
case v7(T7)
/// Eighth of 10
case v8(T8)
/// Ninth of 10
case v9(T9)
/// Tenth of 10
case v10(T10)
@inlinable public init(t1: T1) { self = .v1(t1) }
@inlinable public init(_ t1: T1) { self = .v1(t1) }
@inlinable public init(t2: T2) { self = .v2(t2) }
@inlinable public init(_ t2: T2) { self = .v2(t2) }
@inlinable public init(t3: T3) { self = .v3(t3) }
@inlinable public init(_ t3: T3) { self = .v3(t3) }
@inlinable public init(t4: T4) { self = .v4(t4) }
@inlinable public init(_ t4: T4) { self = .v4(t4) }
@inlinable public init(t5: T5) { self = .v5(t5) }
@inlinable public init(_ t5: T5) { self = .v5(t5) }
@inlinable public init(t6: T6) { self = .v6(t6) }
@inlinable public init(_ t6: T6) { self = .v6(t6) }
@inlinable public init(t7: T7) { self = .v7(t7) }
@inlinable public init(_ t7: T7) { self = .v7(t7) }
@inlinable public init(t8: T8) { self = .v8(t8) }
@inlinable public init(_ t8: T8) { self = .v8(t8) }
@inlinable public init(t9: T9) { self = .v9(t9) }
@inlinable public init(_ t9: T9) { self = .v9(t9) }
@inlinable public init(t10: T10) { self = .v10(t10) }
@inlinable public init(_ t10: T10) { self = .v10(t10) }
@inlinable public var first: T1? { if case .v1(let x) = self { return x } else { return nil } }
@inlinable public var v1: T1? {
get { if case .v1(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v1(x) } }
}
@inlinable public var v2: T2? {
get { if case .v2(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v2(x) } }
}
@inlinable public var v3: T3? {
get { if case .v3(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v3(x) } }
}
@inlinable public var v4: T4? {
get { if case .v4(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v4(x) } }
}
@inlinable public var v5: T5? {
get { if case .v5(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v5(x) } }
}
@inlinable public var v6: T6? {
get { if case .v6(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v6(x) } }
}
@inlinable public var v7: T7? {
get { if case .v7(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v7(x) } }
}
@inlinable public var v8: T8? {
get { if case .v8(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v8(x) } }
}
@inlinable public var v9: T9? {
get { if case .v9(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v9(x) } }
}
@inlinable public var v10: T10? {
get { if case .v10(let x) = self { return x } else { return nil } }
set(x) { if let x = x { self = .v10(x) } }
}
/// Split the tuple into nested Choose2 instances
@inlinable public func split() -> Choose2<Choose2<Choose2<Choose2<Choose2<Choose2<Choose2<Choose2<Choose2<T1, T2>, T3>, T4>, T5>, T6>, T7>, T8>, T9>, T10> {
switch self {
case .v1(let v): return .v1(.v1(.v1(.v1(.v1(.v1(.v1(.v1(.v1(v)))))))))
case .v2(let v): return .v1(.v1(.v1(.v1(.v1(.v1(.v1(.v1(.v2(v)))))))))
case .v3(let v): return .v1(.v1(.v1(.v1(.v1(.v1(.v1(.v2(v))))))))
case .v4(let v): return .v1(.v1(.v1(.v1(.v1(.v1(.v2(v)))))))
case .v5(let v): return .v1(.v1(.v1(.v1(.v1(.v2(v))))))
case .v6(let v): return .v1(.v1(.v1(.v1(.v2(v)))))
case .v7(let v): return .v1(.v1(.v1(.v2(v))))
case .v8(let v): return .v1(.v1(.v2(v)))
case .v9(let v): return .v1(.v2(v))
case .v10(let v): return .v2(v)
}
}
}
public extension Choose10 where T1 == T2, T2 == T3, T3 == T4, T4 == T5, T5 == T6, T6 == T7, T7 == T8, T8 == T9, T9 == T10 {
/// When a ChooseN type wraps the same value types, returns the single value
@inlinable var value: T1 {
switch self {
case .v1(let x): return x
case .v2(let x): return x
case .v3(let x): return x
case .v4(let x): return x
case .v5(let x): return x
case .v6(let x): return x
case .v7(let x): return x
case .v8(let x): return x
case .v9(let x): return x
case .v10(let x): return x
}
}
}
extension Choose10 : Encodable where T1 : Encodable, T2 : Encodable, T3 : Encodable, T4 : Encodable, T5 : Encodable, T6 : Encodable, T7 : Encodable, T8 : Encodable, T9 : Encodable, T10 : Encodable {
@inlinable public func encode(to encoder: Encoder) throws {
switch self {
case .v1(let x): try x.encode(to: encoder)
case .v2(let x): try x.encode(to: encoder)
case .v3(let x): try x.encode(to: encoder)
case .v4(let x): try x.encode(to: encoder)
case .v5(let x): try x.encode(to: encoder)
case .v6(let x): try x.encode(to: encoder)
case .v7(let x): try x.encode(to: encoder)
case .v8(let x): try x.encode(to: encoder)
case .v9(let x): try x.encode(to: encoder)
case .v10(let x): try x.encode(to: encoder)
}
}
}
extension Choose10 : Decodable where T1 : Decodable, T2 : Decodable, T3 : Decodable, T4 : Decodable, T5 : Decodable, T6 : Decodable, T7 : Decodable, T8 : Decodable, T9 : Decodable, T10 : Decodable {
@inlinable public init(from decoder: Decoder) throws {
var errors: [Error] = []
do { self = try .v1(T1(from: decoder)); return } catch { errors.append(error) }
do { self = try .v2(T2(from: decoder)); return } catch { errors.append(error) }
do { self = try .v3(T3(from: decoder)); return } catch { errors.append(error) }
do { self = try .v4(T4(from: decoder)); return } catch { errors.append(error) }
do { self = try .v5(T5(from: decoder)); return } catch { errors.append(error) }
do { self = try .v6(T6(from: decoder)); return } catch { errors.append(error) }
do { self = try .v7(T7(from: decoder)); return } catch { errors.append(error) }
do { self = try .v8(T8(from: decoder)); return } catch { errors.append(error) }
do { self = try .v9(T9(from: decoder)); return } catch { errors.append(error) }
do { self = try .v10(T10(from: decoder)); return } catch { errors.append(error) }
throw ChoiceDecodingError<Choose10>(errors: errors)
}
}
extension Choose10 : Equatable where T1 : Equatable, T2 : Equatable, T3 : Equatable, T4 : Equatable, T5 : Equatable, T6 : Equatable, T7 : Equatable, T8 : Equatable, T9 : Equatable, T10 : Equatable { }
extension Choose10 : Hashable where T1 : Hashable, T2 : Hashable, T3 : Hashable, T4 : Hashable, T5 : Hashable, T6 : Hashable, T7 : Hashable, T8 : Hashable, T9 : Hashable, T10 : Hashable { }
// MARK - Channel either with flatten operation: |
/// Channel either & flattening operation
@inlinable public func |<S1, S2, T1, T2>(lhs: Channel<S1, T1>, rhs: Channel<S2, T2>) -> Channel<(S1, S2), Choose2<T1, T2>> {
return lhs.either(rhs)
}
/// Channel combination & flattening operation
@inlinable public func |<S1, S2, S3, T1, T2, T3>(lhs: Channel<(S1, S2), Choose2<T1, T2>>, rhs: Channel<S3, T3>)->Channel<(S1, S2, S3), Choose3<T1, T2, T3>> {
return combineSources(lhs.either(rhs)).map { choice in
switch choice {
case .v1(.v1(let x)): return .v1(x)
case .v1(.v2(let x)): return .v2(x)
case .v2(let x): return .v3(x)
}
}
}
/// Channel combination & flattening operation
@inlinable public func |<S1, S2, S3, S4, T1, T2, T3, T4>(lhs: Channel<(S1, S2, S3), Choose3<T1, T2, T3>>, rhs: Channel<S4, T4>)->Channel<(S1, S2, S3, S4), Choose4<T1, T2, T3, T4>> {
return combineSources(lhs.either(rhs)).map { choice in
switch choice {
case .v1(.v1(let x)): return .v1(x)
case .v1(.v2(let x)): return .v2(x)
case .v1(.v3(let x)): return .v3(x)
case .v2(let x): return .v4(x)
}
}
}
/// Channel combination & flattening operation
@inlinable public func |<S1, S2, S3, S4, S5, T1, T2, T3, T4, T5>(lhs: Channel<(S1, S2, S3, S4), Choose4<T1, T2, T3, T4>>, rhs: Channel<S5, T5>)->Channel<(S1, S2, S3, S4, S5), Choose5<T1, T2, T3, T4, T5>> {
return combineSources(lhs.either(rhs)).map { choice in
switch choice {
case .v1(.v1(let x)): return .v1(x)
case .v1(.v2(let x)): return .v2(x)
case .v1(.v3(let x)): return .v3(x)
case .v1(.v4(let x)): return .v4(x)
case .v2(let x): return .v5(x)
}
}
}
/// Channel combination & flattening operation
@inlinable public func |<S1, S2, S3, S4, S5, S6, T1, T2, T3, T4, T5, T6>(lhs: Channel<(S1, S2, S3, S4, S5), Choose5<T1, T2, T3, T4, T5>>, rhs: Channel<S6, T6>)->Channel<(S1, S2, S3, S4, S5, S6), Choose6<T1, T2, T3, T4, T5, T6>> {
return combineSources(lhs.either(rhs)).map { choice in
switch choice {
case .v1(.v1(let x)): return .v1(x)
case .v1(.v2(let x)): return .v2(x)
case .v1(.v3(let x)): return .v3(x)
case .v1(.v4(let x)): return .v4(x)
case .v1(.v5(let x)): return .v5(x)
case .v2(let x): return .v6(x)
}
}
}
/// Channel combination & flattening operation
@inlinable public func |<S1, S2, S3, S4, S5, S6, S7, T1, T2, T3, T4, T5, T6, T7>(lhs: Channel<(S1, S2, S3, S4, S5, S6), Choose6<T1, T2, T3, T4, T5, T6>>, rhs: Channel<S7, T7>)->Channel<(S1, S2, S3, S4, S5, S6, S7), Choose7<T1, T2, T3, T4, T5, T6, T7>> {
return combineSources(lhs.either(rhs)).map { choice in
switch choice {
case .v1(.v1(let x)): return .v1(x)
case .v1(.v2(let x)): return .v2(x)
case .v1(.v3(let x)): return .v3(x)
case .v1(.v4(let x)): return .v4(x)
case .v1(.v5(let x)): return .v5(x)
case .v1(.v6(let x)): return .v6(x)
case .v2(let x): return .v7(x)
}
}
}
/// Channel combination & flattening operation
@inlinable public func |<S1, S2, S3, S4, S5, S6, S7, S8, T1, T2, T3, T4, T5, T6, T7, T8>(lhs: Channel<(S1, S2, S3, S4, S5, S6, S7), Choose7<T1, T2, T3, T4, T5, T6, T7>>, rhs: Channel<S8, T8>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8), Choose8<T1, T2, T3, T4, T5, T6, T7, T8>> {
return combineSources(lhs.either(rhs)).map { choice in
switch choice {
case .v1(.v1(let x)): return .v1(x)
case .v1(.v2(let x)): return .v2(x)
case .v1(.v3(let x)): return .v3(x)
case .v1(.v4(let x)): return .v4(x)
case .v1(.v5(let x)): return .v5(x)
case .v1(.v6(let x)): return .v6(x)
case .v1(.v7(let x)): return .v7(x)
case .v2(let x): return .v8(x)
}
}
}
/// Channel combination & flattening operation
@inlinable public func |<S1, S2, S3, S4, S5, S6, S7, S8, S9, T1, T2, T3, T4, T5, T6, T7, T8, T9>(lhs: Channel<(S1, S2, S3, S4, S5, S6, S7, S8), Choose8<T1, T2, T3, T4, T5, T6, T7, T8>>, rhs: Channel<S9, T9>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9), Choose9<T1, T2, T3, T4, T5, T6, T7, T8, T9>> {
return combineSources(lhs.either(rhs)).map { choice in
switch choice {
case .v1(.v1(let x)): return .v1(x)
case .v1(.v2(let x)): return .v2(x)
case .v1(.v3(let x)): return .v3(x)
case .v1(.v4(let x)): return .v4(x)
case .v1(.v5(let x)): return .v5(x)
case .v1(.v6(let x)): return .v6(x)
case .v1(.v7(let x)): return .v7(x)
case .v1(.v8(let x)): return .v8(x)
case .v2(let x): return .v9(x)
}
}
}
/// Channel combination & flattening operation
@inlinable public func |<S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(lhs: Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9), Choose9<T1, T2, T3, T4, T5, T6, T7, T8, T9>>, rhs: Channel<S10, T10>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9, S10), Choose10<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>> {
return combineSources(lhs.either(rhs)).map { choice in
switch choice {
case .v1(.v1(let x)): return .v1(x)
case .v1(.v2(let x)): return .v2(x)
case .v1(.v3(let x)): return .v3(x)
case .v1(.v4(let x)): return .v4(x)
case .v1(.v5(let x)): return .v5(x)
case .v1(.v6(let x)): return .v6(x)
case .v1(.v7(let x)): return .v7(x)
case .v1(.v8(let x)): return .v8(x)
case .v1(.v9(let x)): return .v9(x)
case .v2(let x): return .v10(x)
}
}
}
// MARK - Channel combine with flatten operation: &
/// Channel `combine` & flattening operation
@inlinable public func &<S1, S2, T1, T2>(lhs: Channel<S1, T1>, rhs: Channel<S2, T2>) -> Channel<(S1, S2), (T1, T2)> {
return lhs.combine(rhs)
}
/// Channel `combine` & flattening operation
@inlinable public func &<S1, S2, S3, T1, T2, T3>(lhs: Channel<(S1, S2), (T1, T2)>, rhs: Channel<S3, T3>)->Channel<(S1, S2, S3), (T1, T2, T3)> { return combineSources(combineAll(lhs.combine(rhs))) }
/// Channel `combine` & flattening operation
@inlinable public func &<S1, S2, S3, S4, T1, T2, T3, T4>(lhs: Channel<(S1, S2, S3), (T1, T2, T3)>, rhs: Channel<S4, T4>)->Channel<(S1, S2, S3, S4), (T1, T2, T3, T4)> { return combineSources(combineAll(lhs.combine(rhs))) }
/// Channel `combine` & flattening operation
@inlinable public func &<S1, S2, S3, S4, S5, T1, T2, T3, T4, T5>(lhs: Channel<(S1, S2, S3, S4), (T1, T2, T3, T4)>, rhs: Channel<S5, T5>)->Channel<(S1, S2, S3, S4, S5), (T1, T2, T3, T4, T5)> { return combineSources(combineAll(lhs.combine(rhs))) }
/// Channel `combine` & flattening operation
@inlinable public func &<S1, S2, S3, S4, S5, S6, T1, T2, T3, T4, T5, T6>(lhs: Channel<(S1, S2, S3, S4, S5), (T1, T2, T3, T4, T5)>, rhs: Channel<S6, T6>)->Channel<(S1, S2, S3, S4, S5, S6), (T1, T2, T3, T4, T5, T6)> { return combineSources(combineAll(lhs.combine(rhs))) }
/// Channel `combine` & flattening operation
@inlinable public func &<S1, S2, S3, S4, S5, S6, S7, T1, T2, T3, T4, T5, T6, T7>(lhs: Channel<(S1, S2, S3, S4, S5, S6), (T1, T2, T3, T4, T5, T6)>, rhs: Channel<S7, T7>)->Channel<(S1, S2, S3, S4, S5, S6, S7), (T1, T2, T3, T4, T5, T6, T7)> { return combineSources(combineAll(lhs.combine(rhs))) }
/// Channel `combine` & flattening operation
@inlinable public func &<S1, S2, S3, S4, S5, S6, S7, S8, T1, T2, T3, T4, T5, T6, T7, T8>(lhs: Channel<(S1, S2, S3, S4, S5, S6, S7), (T1, T2, T3, T4, T5, T6, T7)>, rhs: Channel<S8, T8>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8), (T1, T2, T3, T4, T5, T6, T7, T8)> { return combineSources(combineAll(lhs.combine(rhs))) }
/// Channel `combine` & flattening operation
@inlinable public func &<S1, S2, S3, S4, S5, S6, S7, S8, S9, T1, T2, T3, T4, T5, T6, T7, T8, T9>(lhs: Channel<(S1, S2, S3, S4, S5, S6, S7, S8), (T1, T2, T3, T4, T5, T6, T7, T8)>, rhs: Channel<S9, T9>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9), (T1, T2, T3, T4, T5, T6, T7, T8, T9)> { return combineSources(combineAll(lhs.combine(rhs))) }
/// Channel `combine` & flattening operation
@inlinable public func &<S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(lhs: Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9), (T1, T2, T3, T4, T5, T6, T7, T8, T9)>, rhs: Channel<S10, T10>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9, S10), (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)> { return combineSources(combineAll(lhs.combine(rhs))) }
// MARK - Channel zip with flatten operation: ^
/// Channel zipping & flattening operation
@inlinable public func ^<S1, S2, T1, T2>(lhs: Channel<S1, T1>, rhs: Channel<S2, T2>) -> Channel<(S1, S2), (T1, T2)> {
return lhs.zip(rhs)
}
/// Channel zipping & flattening operation
@inlinable public func ^<S1, S2, S3, T1, T2, T3>(lhs: Channel<(S1, S2), (T1, T2)>, rhs: Channel<S3, T3>)->Channel<(S1, S2, S3), (T1, T2, T3)> { return combineSources(combineAll(lhs.zip(rhs))) }
/// Channel zipping & flattening operation
@inlinable public func ^<S1, S2, S3, S4, T1, T2, T3, T4>(lhs: Channel<(S1, S2, S3), (T1, T2, T3)>, rhs: Channel<S4, T4>)->Channel<(S1, S2, S3, S4), (T1, T2, T3, T4)> { return combineSources(combineAll(lhs.zip(rhs))) }
/// Channel zipping & flattening operation
@inlinable public func ^<S1, S2, S3, S4, S5, T1, T2, T3, T4, T5>(lhs: Channel<(S1, S2, S3, S4), (T1, T2, T3, T4)>, rhs: Channel<S5, T5>)->Channel<(S1, S2, S3, S4, S5), (T1, T2, T3, T4, T5)> { return combineSources(combineAll(lhs.zip(rhs))) }
/// Channel zipping & flattening operation
@inlinable public func ^<S1, S2, S3, S4, S5, S6, T1, T2, T3, T4, T5, T6>(lhs: Channel<(S1, S2, S3, S4, S5), (T1, T2, T3, T4, T5)>, rhs: Channel<S6, T6>)->Channel<(S1, S2, S3, S4, S5, S6), (T1, T2, T3, T4, T5, T6)> { return combineSources(combineAll(lhs.zip(rhs))) }
/// Channel zipping & flattening operation
@inlinable public func ^<S1, S2, S3, S4, S5, S6, S7, T1, T2, T3, T4, T5, T6, T7>(lhs: Channel<(S1, S2, S3, S4, S5, S6), (T1, T2, T3, T4, T5, T6)>, rhs: Channel<S7, T7>)->Channel<(S1, S2, S3, S4, S5, S6, S7), (T1, T2, T3, T4, T5, T6, T7)> { return combineSources(combineAll(lhs.zip(rhs))) }
/// Channel zipping & flattening operation
@inlinable public func ^<S1, S2, S3, S4, S5, S6, S7, S8, T1, T2, T3, T4, T5, T6, T7, T8>(lhs: Channel<(S1, S2, S3, S4, S5, S6, S7), (T1, T2, T3, T4, T5, T6, T7)>, rhs: Channel<S8, T8>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8), (T1, T2, T3, T4, T5, T6, T7, T8)> { return combineSources(combineAll(lhs.zip(rhs))) }
/// Channel zipping & flattening operation
@inlinable public func ^<S1, S2, S3, S4, S5, S6, S7, S8, S9, T1, T2, T3, T4, T5, T6, T7, T8, T9>(lhs: Channel<(S1, S2, S3, S4, S5, S6, S7, S8), (T1, T2, T3, T4, T5, T6, T7, T8)>, rhs: Channel<S9, T9>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9), (T1, T2, T3, T4, T5, T6, T7, T8, T9)> { return combineSources(combineAll(lhs.zip(rhs))) }
/// Channel zipping & flattening operation
@inlinable public func ^<S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(lhs: Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9), (T1, T2, T3, T4, T5, T6, T7, T8, T9)>, rhs: Channel<S10, T10>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9, S10), (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)> { return combineSources(combineAll(lhs.zip(rhs))) }
@usableFromInline func combineSources<S1, S2, S3, T>(_ rcvr: Channel<((S1, S2), S3), T>)->Channel<(S1, S2, S3), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.1) } }
@usableFromInline func combineSources<S1, S2, S3, S4, T>(_ rcvr: Channel<((S1, S2, S3), S4), T>)->Channel<(S1, S2, S3, S4), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.0.2, src.1) } }
@usableFromInline func combineSources<S1, S2, S3, S4, S5, T>(_ rcvr: Channel<((S1, S2, S3, S4), S5), T>)->Channel<(S1, S2, S3, S4, S5), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.0.2, src.0.3, src.1) } }
@usableFromInline func combineSources<S1, S2, S3, S4, S5, S6, T>(_ rcvr: Channel<((S1, S2, S3, S4, S5), S6), T>)->Channel<(S1, S2, S3, S4, S5, S6), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.0.2, src.0.3, src.0.4, src.1) } }
@usableFromInline func combineSources<S1, S2, S3, S4, S5, S6, S7, T>(_ rcvr: Channel<((S1, S2, S3, S4, S5, S6), S7), T>)->Channel<(S1, S2, S3, S4, S5, S6, S7), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.0.2, src.0.3, src.0.4, src.0.5, src.1) } }
@usableFromInline func combineSources<S1, S2, S3, S4, S5, S6, S7, S8, T>(_ rcvr: Channel<((S1, S2, S3, S4, S5, S6, S7), S8), T>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.0.2, src.0.3, src.0.4, src.0.5, src.0.6, src.1) } }
@usableFromInline func combineSources<S1, S2, S3, S4, S5, S6, S7, S8, S9, T>(_ rcvr: Channel<((S1, S2, S3, S4, S5, S6, S7, S8), S9), T>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.0.2, src.0.3, src.0.4, src.0.5, src.0.6, src.0.7, src.1) } }
@usableFromInline func combineSources<S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, T>(_ rcvr: Channel<((S1, S2, S3, S4, S5, S6, S7, S8, S9), S10), T>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9, S10), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.0.2, src.0.3, src.0.4, src.0.5, src.0.6, src.0.7, src.0.8, src.1) } }
@usableFromInline func combineSources<S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, T>(_ rcvr: Channel<((S1, S2, S3, S4, S5, S6, S7, S8, S9, S10), S11), T>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.0.2, src.0.3, src.0.4, src.0.5, src.0.6, src.0.7, src.0.8, src.0.9, src.1) } }
@usableFromInline func combineSources<S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, T>(_ rcvr: Channel<((S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11), S12), T>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.0.2, src.0.3, src.0.4, src.0.5, src.0.6, src.0.7, src.0.8, src.0.9, src.0.10, src.1) } }
@usableFromInline func combineSources<S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, T>(_ rcvr: Channel<((S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12), S13), T>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.0.2, src.0.3, src.0.4, src.0.5, src.0.6, src.0.7, src.0.8, src.0.9, src.0.10, src.0.11, src.1) } }
@usableFromInline func combineSources<S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, T>(_ rcvr: Channel<((S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13), S14), T>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.0.2, src.0.3, src.0.4, src.0.5, src.0.6, src.0.7, src.0.8, src.0.9, src.0.10, src.0.11, src.0.12, src.1) } }
@usableFromInline func combineSources<S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, T>(_ rcvr: Channel<((S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14), S15), T>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.0.2, src.0.3, src.0.4, src.0.5, src.0.6, src.0.7, src.0.8, src.0.9, src.0.10, src.0.11, src.0.12, src.0.13, src.1) } }
@usableFromInline func combineSources<S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, T>(_ rcvr: Channel<((S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15), S16), T>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.0.2, src.0.3, src.0.4, src.0.5, src.0.6, src.0.7, src.0.8, src.0.9, src.0.10, src.0.11, src.0.12, src.0.13, src.0.14, src.1) } }
@usableFromInline func combineSources<S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, T>(_ rcvr: Channel<((S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16), S17), T>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.0.2, src.0.3, src.0.4, src.0.5, src.0.6, src.0.7, src.0.8, src.0.9, src.0.10, src.0.11, src.0.12, src.0.13, src.0.14, src.0.15, src.1) } }
@usableFromInline func combineSources<S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, T>(_ rcvr: Channel<((S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17), S18), T>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.0.2, src.0.3, src.0.4, src.0.5, src.0.6, src.0.7, src.0.8, src.0.9, src.0.10, src.0.11, src.0.12, src.0.13, src.0.14, src.0.15, src.0.16, src.1) } }
@usableFromInline func combineSources<S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19, T>(_ rcvr: Channel<((S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18), S19), T>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.0.2, src.0.3, src.0.4, src.0.5, src.0.6, src.0.7, src.0.8, src.0.9, src.0.10, src.0.11, src.0.12, src.0.13, src.0.14, src.0.15, src.0.16, src.0.17, src.1) } }
@usableFromInline func combineSources<S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19, S20, T>(_ rcvr: Channel<((S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19), S20), T>)->Channel<(S1, S2, S3, S4, S5, S6, S7, S8, S9, S10, S11, S12, S13, S14, S15, S16, S17, S18, S19, S20), T> { return rcvr.resource { src in (src.0.0, src.0.1, src.0.2, src.0.3, src.0.4, src.0.5, src.0.6, src.0.7, src.0.8, src.0.9, src.0.10, src.0.11, src.0.12, src.0.13, src.0.14, src.0.15, src.0.16, src.0.17, src.0.18, src.1) } }
@usableFromInline func combineAll<S, T1, T2, T3>(_ rcvr: Channel<S, ((T1, T2), T3)>)->Channel<S, (T1, T2, T3)> { return rcvr.map { ($0.0.0, $0.0.1, $0.1) } }
@usableFromInline func combineAll<S, T1, T2, T3, T4>(_ rcvr: Channel<S, ((T1, T2, T3), T4)>)->Channel<S, (T1, T2, T3, T4)> { return rcvr.map { ($0.0.0, $0.0.1, $0.0.2, $0.1) } }
@usableFromInline func combineAll<S, T1, T2, T3, T4, T5>(_ rcvr: Channel<S, ((T1, T2, T3, T4), T5)>)->Channel<S, (T1, T2, T3, T4, T5)> { return rcvr.map { ($0.0.0, $0.0.1, $0.0.2, $0.0.3, $0.1) } }
@usableFromInline func combineAll<S, T1, T2, T3, T4, T5, T6>(_ rcvr: Channel<S, ((T1, T2, T3, T4, T5), T6)>)->Channel<S, (T1, T2, T3, T4, T5, T6)> { return rcvr.map { ($0.0.0, $0.0.1, $0.0.2, $0.0.3, $0.0.4, $0.1) } }
@usableFromInline func combineAll<S, T1, T2, T3, T4, T5, T6, T7>(_ rcvr: Channel<S, ((T1, T2, T3, T4, T5, T6), T7)>)->Channel<S, (T1, T2, T3, T4, T5, T6, T7)> { return rcvr.map { ($0.0.0, $0.0.1, $0.0.2, $0.0.3, $0.0.4, $0.0.5, $0.1) } }
@usableFromInline func combineAll<S, T1, T2, T3, T4, T5, T6, T7, T8>(_ rcvr: Channel<S, ((T1, T2, T3, T4, T5, T6, T7), T8)>)->Channel<S, (T1, T2, T3, T4, T5, T6, T7, T8)> { return rcvr.map { ($0.0.0, $0.0.1, $0.0.2, $0.0.3, $0.0.4, $0.0.5, $0.0.6, $0.1) } }
@usableFromInline func combineAll<S, T1, T2, T3, T4, T5, T6, T7, T8, T9>(_ rcvr: Channel<S, ((T1, T2, T3, T4, T5, T6, T7, T8), T9)>)->Channel<S, (T1, T2, T3, T4, T5, T6, T7, T8, T9)> { return rcvr.map { ($0.0.0, $0.0.1, $0.0.2, $0.0.3, $0.0.4, $0.0.5, $0.0.6, $0.0.7, $0.1) } }
@usableFromInline func combineAll<S, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(_ rcvr: Channel<S, ((T1, T2, T3, T4, T5, T6, T7, T8, T9), T10)>)->Channel<S, (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10)> { return rcvr.map { ($0.0.0, $0.0.1, $0.0.2, $0.0.3, $0.0.4, $0.0.5, $0.0.6, $0.0.7, $0.0.8, $0.1) } }
| mit |
I-SYST/EHAL | OSX/exemples/SensorTagDemo/SensorTagDemoTests/SensorTagDemoTests.swift | 1 | 1001 | //
// SensorTagDemoTests.swift
// SensorTagDemoTests
//
// Created by Nguyen Hoan Hoang on 2017-10-22.
// Copyright © 2017 I-SYST inc. All rights reserved.
//
import XCTest
@testable import SensorTagDemo
class SensorTagDemoTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| bsd-3-clause |
gecko655/Swifter | Sources/SwifterAuth.swift | 2 | 9166 | //
// SwifterAuth.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
#if os(iOS)
import UIKit
import SafariServices
#else
import AppKit
#endif
public extension Swifter {
public typealias TokenSuccessHandler = (Credential.OAuthAccessToken?, URLResponse) -> Void
/**
Begin Authorization with a Callback URL.
- OS X only
*/
#if os(OSX)
public func authorize(with callbackURL: URL, success: TokenSuccessHandler?, failure: FailureHandler? = nil) {
self.postOAuthRequestToken(with: callbackURL, success: { token, response in
var requestToken = token!
NotificationCenter.default.addObserver(forName: .SwifterCallbackNotification, object: nil, queue: .main) { notification in
NotificationCenter.default.removeObserver(self)
let url = notification.userInfo![CallbackNotification.optionsURLKey] as! URL
let parameters = url.query!.queryStringParameters
requestToken.verifier = parameters["oauth_verifier"]
self.postOAuthAccessToken(with: requestToken, success: { accessToken, response in
self.client.credential = Credential(accessToken: accessToken!)
success?(accessToken!, response)
}, failure: failure)
}
let authorizeURL = URL(string: "oauth/authorize", relativeTo: TwitterURL.oauth.url)
let queryURL = URL(string: authorizeURL!.absoluteString + "?oauth_token=\(token!.key)")!
NSWorkspace.shared().open(queryURL)
}, failure: failure)
}
#endif
/**
Begin Authorization with a Callback URL
- Parameter presentFromViewController: The viewController used to present the SFSafariViewController.
The UIViewController must inherit SFSafariViewControllerDelegate
*/
#if os(iOS)
public func authorize(with callbackURL: URL, presentFrom presentingViewController: UIViewController? , success: TokenSuccessHandler?, failure: FailureHandler? = nil) {
self.postOAuthRequestToken(with: callbackURL, success: { token, response in
var requestToken = token!
NotificationCenter.default.addObserver(forName: .SwifterCallbackNotification, object: nil, queue: .main) { notification in
NotificationCenter.default.removeObserver(self)
presentingViewController?.presentedViewController?.dismiss(animated: true, completion: nil)
let url = notification.userInfo![CallbackNotification.optionsURLKey] as! URL
let parameters = url.query!.queryStringParameters
requestToken.verifier = parameters["oauth_verifier"]
self.postOAuthAccessToken(with: requestToken, success: { accessToken, response in
self.client.credential = Credential(accessToken: accessToken!)
success?(accessToken!, response)
}, failure: failure)
}
let authorizeURL = URL(string: "oauth/authorize", relativeTo: TwitterURL.oauth.url)
let queryURL = URL(string: authorizeURL!.absoluteString + "?oauth_token=\(token!.key)")!
if #available(iOS 9.0, *) , let delegate = presentingViewController as? SFSafariViewControllerDelegate {
let safariView = SFSafariViewController(url: queryURL)
safariView.delegate = delegate
presentingViewController?.present(safariView, animated: true, completion: nil)
} else {
UIApplication.shared.openURL(queryURL)
}
}, failure: failure)
}
#endif
public class func handleOpenURL(_ url: URL) {
let notification = Notification(name: .SwifterCallbackNotification, object: nil, userInfo: [CallbackNotification.optionsURLKey: url])
NotificationCenter.default.post(notification)
}
public func authorizeAppOnly(success: TokenSuccessHandler?, failure: FailureHandler?) {
self.postOAuth2BearerToken(success: { json, response in
if let tokenType = json["token_type"].string {
if tokenType == "bearer" {
let accessToken = json["access_token"].string
let credentialToken = Credential.OAuthAccessToken(key: accessToken!, secret: "")
self.client.credential = Credential(accessToken: credentialToken)
success?(credentialToken, response)
} else {
let error = SwifterError(message: "Cannot find bearer token in server response", kind: .invalidAppOnlyBearerToken)
failure?(error)
}
} else if case .object = json["errors"] {
let error = SwifterError(message: json["errors"]["message"].string!, kind: .responseError(code: json["errors"]["code"].integer!))
failure?(error)
} else {
let error = SwifterError(message: "Cannot find JSON dictionary in response", kind: .invalidJSONResponse)
failure?(error)
}
}, failure: failure)
}
public func postOAuth2BearerToken(success: JSONSuccessHandler?, failure: FailureHandler?) {
let path = "oauth2/token"
var parameters = Dictionary<String, Any>()
parameters["grant_type"] = "client_credentials"
self.jsonRequest(path: path, baseURL: .oauth, method: .POST, parameters: parameters, success: success, failure: failure)
}
public func invalidateOAuth2BearerToken(success: TokenSuccessHandler?, failure: FailureHandler?) {
let path = "oauth2/invalidate_token"
self.jsonRequest(path: path, baseURL: .oauth, method: .POST, parameters: [:], success: { json, response in
if let accessToken = json["access_token"].string {
self.client.credential = nil
let credentialToken = Credential.OAuthAccessToken(key: accessToken, secret: "")
success?(credentialToken, response)
} else {
success?(nil, response)
}
}, failure: failure)
}
public func postOAuthRequestToken(with callbackURL: URL, success: @escaping TokenSuccessHandler, failure: FailureHandler?) {
let path = "oauth/request_token"
let parameters: [String: Any] = ["oauth_callback": callbackURL.absoluteString]
self.client.post(path, baseURL: .oauth, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { data, response in
let responseString = String(data: data, encoding: .utf8)!
let accessToken = Credential.OAuthAccessToken(queryString: responseString)
success(accessToken, response)
}, failure: failure)
}
public func postOAuthAccessToken(with requestToken: Credential.OAuthAccessToken, success: @escaping TokenSuccessHandler, failure: FailureHandler?) {
if let verifier = requestToken.verifier {
let path = "oauth/access_token"
let parameters: [String: Any] = ["oauth_token": requestToken.key, "oauth_verifier": verifier]
self.client.post(path, baseURL: .oauth, parameters: parameters, uploadProgress: nil, downloadProgress: nil, success: { data, response in
let responseString = String(data: data, encoding: .utf8)!
let accessToken = Credential.OAuthAccessToken(queryString: responseString)
success(accessToken, response)
}, failure: failure)
} else {
let error = SwifterError(message: "Bad OAuth response received from server", kind: .badOAuthResponse)
failure?(error)
}
}
}
| mit |
CocoaheadsSaar/Treffen | Treffen1/Swift_Buildpack_for_Cloud_Foundry/web_app_hello_world/Package.swift | 1 | 186 | import PackageDescription
let package = Package(
name: "myapp",
dependencies: [
.Package(url: "https://github.com/kylef/Curassow.git", majorVersion: 0, minor: 2)
]
) | gpl-2.0 |
hooman/swift | test/Driver/Dependencies/one-way-parallel-fine.swift | 9 | 2503 | // Windows doesn't support parallel execution yet
// XFAIL: windows
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/one-way-fine/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j1 -parseable-output 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// CHECK-FIRST-NOT: warning
// CHECK-FIRST: {{^{$}}
// CHECK-FIRST-DAG: "kind"{{ *}}: "began"
// CHECK-FIRST-DAG: "name"{{ *}}: "compile"
// CHECK-FIRST-DAG: "{{(.\\/)?}}main.swift"
// CHECK-FIRST: {{^}$}}
// CHECK-FIRST: {{^{$}}
// CHECK-FIRST-DAG: "kind"{{ *}}: "finished"
// CHECK-FIRST-DAG: "name"{{ *}}: "compile"
// CHECK-FIRST-DAG: "output"{{ *}}: "Handled main.swift\n"
// CHECK-FIRST: {{^}$}}
// CHECK-FIRST: {{^{$}}
// CHECK-FIRST-DAG: "kind"{{ *}}: "began"
// CHECK-FIRST-DAG: "name"{{ *}}: "compile"
// CHECK-FIRST-DAG: "{{(.\\/)?}}other.swift"
// CHECK-FIRST: {{^}$}}
// CHECK-FIRST: {{^{$}}
// CHECK-FIRST-DAG: "kind"{{ *}}: "finished"
// CHECK-FIRST-DAG: "name"{{ *}}: "compile"
// CHECK-FIRST-DAG: "output"{{ *}}: "Handled other.swift\n"
// CHECK-FIRST: {{^}$}}
// RUN: touch -t 201401240006 %t/other.swift
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python.unquoted};%S/Inputs/update-dependencies.py;%swift-dependency-tool" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift -module-name main -j2 -parseable-output 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s
// CHECK-SECOND: {{^{$}}
// CHECK-SECOND-DAG: "kind"{{ *}}: "began"
// CHECK-SECOND-DAG: "name"{{ *}}: "compile"
// CHECK-SECOND-DAG: "{{(.\\/)?}}other.swift"
// CHECK-SECOND: {{^}$}}
// CHECK-SECOND: {{^{$}}
// CHECK-SECOND-DAG: "kind"{{ *}}: "began"
// CHECK-SECOND-DAG: "name"{{ *}}: "compile"
// CHECK-SECOND-DAG: "{{(.\\/)?}}main.swift"
// CHECK-SECOND: {{^}$}}
// CHECK-SECOND: {{^{$}}
// CHECK-SECOND-DAG: "kind"{{ *}}: "finished"
// CHECK-SECOND-DAG: "name"{{ *}}: "compile"
// CHECK-SECOND-DAG: "output"{{ *}}: "Handled {{other.swift|main.swift}}\n"
// CHECK-SECOND: {{^}$}}
// CHECK-SECOND: {{^{$}}
// CHECK-SECOND-DAG: "kind"{{ *}}: "finished"
// CHECK-SECOND-DAG: "name"{{ *}}: "compile"
// CHECK-SECOND-DAG: "output"{{ *}}: "Handled {{main.swift|other.swift}}\n"
// CHECK-SECOND: {{^}$}}
// CHECK-SECOND-NOT: "skipped"
| apache-2.0 |
EclipseSoundscapes/EclipseSoundscapes | EclipseSoundscapes/Extensions/View+NibExtensions.swift | 1 | 597 | //
// View+NibExtensions.swift
// EclipseSoundscapes
//
// Created by Arlindo on 12/2/20.
// Copyright © 2020 Eclipse Soundscapes. All rights reserved.
//
import UIKit
protocol NibView {}
extension UIView: NibView {}
extension NibView {
static func loadFromNib(in bundle: Bundle = .main,
name: String? = nil) -> Self? {
let nibName = (name ?? String(describing: self))
return bundle.loadNibNamed(
nibName,
owner: nil,
options: nil
)?
.filter {$0 is Self }
.first as? Self
}
}
| gpl-3.0 |
kentaiwami/FiNote | ios/FiNote/FiNote/Movie/Movies/MoviesUserInfoViewController.swift | 1 | 7628 | //
// MoviesUserInfoViewController.swift
// FiNote
//
// Created by 岩見建汰 on 2018/01/26.
// Copyright © 2018年 Kenta. All rights reserved.
//
import UIKit
import Eureka
import NVActivityIndicatorView
import Alamofire
import SwiftyJSON
import KeychainAccess
class MoviesUserInfoViewController: FormViewController {
var MovieCommonFunc = MovieCommon()
var movie_id = 0
var onomatopoeia: [String] = []
var dvd = false
var fav = false
var count = 1
var choices: [String] = []
fileprivate let utility = Utility()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "Edit Info"
let close = UIBarButtonItem(image: UIImage(named: "icon_cancel"), style: .plain, target: self, action: #selector(TapCloseButton))
let save = UIBarButtonItem(image: UIImage(named: "icon_check"), style: .plain, target: self, action: #selector(TapSaveButton))
self.navigationItem.setLeftBarButton(close, animated: true)
self.navigationItem.setRightBarButton(save, animated: true)
MovieCommonFunc.CallGetOnomatopoeiaAPI(act: { obj in
self.choices = obj["results"].arrayValue.map{$0.stringValue}
self.CreateForm()
}, vc: self)
}
@objc func TapCloseButton() {
self.dismiss(animated: true, completion: nil)
}
@objc func TapSaveButton() {
let choosing = MovieCommonFunc.GetChoosingOnomatopoeia(values: form.values())
if choosing.count == 0 {
utility.showStandardAlert(title: "Error", msg: "オノマトペは少なくとも1つ以上追加する必要があります", vc: self)
}else {
CallUpdateMovieUserInfoAPI()
}
}
func SetMovieID(movie_id: Int) {
self.movie_id = movie_id
}
func SetOnomatopoeia(onomatopoeia: [String]) {
self.onomatopoeia = onomatopoeia
}
func SetDVD(dvd: Bool) {
self.dvd = dvd
}
func SetFAV(fav: Bool) {
self.fav = fav
}
func CreateForm() {
UIView.setAnimationsEnabled(false)
form +++ Section(header: "DVDの所持・お気に入り登録", footer: "")
<<< SwitchRow("") { row in
row.title = "DVD"
row.value = dvd
row.tag = "dvd"
}
<<< SwitchRow("") { row in
row.title = "Favorite"
row.value = fav
row.tag = "fav"
}
form +++ MultivaluedSection(
multivaluedOptions: [.Insert, .Delete],
header: "オノマトペの登録",
footer: "映画を観た気分を登録してください") {
$0.tag = "onomatopoeia"
$0.multivaluedRowToInsertAt = { _ in
let options = self.MovieCommonFunc.GetOnomatopoeiaNewChoices(values: self.form.values(), choices: self.choices)
if options.count == 0 {
return PickerInputRow<String>{
$0.title = "タップして選択..."
$0.options = options
$0.value = ""
$0.tag = "onomatopoeia_\(self.count)"
self.count += 1
}.onCellSelection({ (cell, row) in
row.options = self.MovieCommonFunc.GetOnomatopoeiaNewChoices(ignore: row.value!, values: self.form.values(), choices: self.choices)
row.updateCell()
})
}else {
return PickerInputRow<String>{
$0.title = "タップして選択..."
$0.options = options
$0.value = options.first!
$0.tag = "onomatopoeia_\(self.count)"
self.count += 1
}.onCellSelection({ (cell, row) in
row.options = self.MovieCommonFunc.GetOnomatopoeiaNewChoices(ignore: row.value!, values: self.form.values(), choices: self.choices)
row.updateCell()
})
}
}
for (i, name) in onomatopoeia.enumerated() {
$0 <<< PickerInputRow<String> {
$0.title = "タップして選択..."
$0.value = name
$0.options = MovieCommonFunc.GetOnomatopoeiaNewChoices(values: self.form.values(), choices: self.choices)
$0.tag = "onomatopoeia_\(i)"
}.onCellSelection({ (cell, row) in
row.options = self.MovieCommonFunc.GetOnomatopoeiaNewChoices(ignore: row.value!, values: self.form.values(), choices: self.choices)
row.updateCell()
})
count = i+1
}
}
UIView.setAnimationsEnabled(true)
}
func CallUpdateMovieUserInfoAPI() {
let urlString = API.base.rawValue+API.v1.rawValue+API.movie.rawValue+API.update.rawValue
let activityData = ActivityData(message: "Updating", type: .lineScaleParty)
let keychain = Keychain()
let appdelegate = utility.getAppDelegate()
let choosing_onomatopoeia = NSOrderedSet(array: MovieCommonFunc.GetChoosingOnomatopoeia(values: form.values())).array as! [String]
let params = [
"username": (try! keychain.getString("username"))!,
"password": (try! keychain.getString("password"))!,
"tmdb_id": movie_id,
"dvd": form.values()["dvd"] as! Bool,
"fav": form.values()["fav"] as! Bool,
"onomatopoeia": choosing_onomatopoeia
] as [String : Any]
NVActivityIndicatorPresenter.sharedInstance.startAnimating(activityData, nil)
DispatchQueue(label: "update-movie-user-info").async {
Alamofire.request(urlString, method: .post, parameters: params, encoding: JSONEncoding.default).responseJSON { (response) in
NVActivityIndicatorPresenter.sharedInstance.stopAnimating(nil)
guard let res = response.result.value else{return}
let obj = JSON(res)
print("***** API results *****")
print(obj)
print("***** API results *****")
if self.utility.isHTTPStatus(statusCode: response.response?.statusCode) {
let index = appdelegate.movies.firstIndex(where: {$0.id == self.movie_id})
let index_int = index?.advanced(by: 0)
appdelegate.movies[index_int!].onomatopoeia = choosing_onomatopoeia
// MovieInfo画面を閉じる前にMovieDetail画面でpop(Moviesへ遷移)
let nav = self.presentingViewController as! UINavigationController
nav.popViewController(animated: true)
self.dismiss(animated: true, completion: nil)
}else {
self.utility.showStandardAlert(title: "Error", msg: obj.arrayValue[0].stringValue, vc: self)
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| mit |
benlangmuir/swift | test/DebugInfo/optimizer_pipeline.swift | 4 | 962 | // RUN: %target-swift-frontend %s -emit-sil -g -Osize -parse-stdlib -parse-as-library -enable-ossa-modules -o - | %FileCheck %s
// REQUIRES: asserts
import Swift
// Test that DCE correctly preserves debug locations.
// https://github.com/apple/swift/issues/57622
// Compiler crash when using 'Builtin.unreachable' in initializers
//
// CHECK: sil_scope [[S1:[0-9]+]] { {{.*}} parent @$s18optimizer_pipeline1AVyACs13KeyValuePairsVyypypGcfC
// CHECK: sil_scope [[S2:[0-9]+]] { {{.*}} parent [[S1]] }
//
// CHECK-LABEL: sil {{.*}}@$s18optimizer_pipeline1AVyACs13KeyValuePairsVyypypGcfC : $@convention(method) (@owned KeyValuePairs<Any, Any>, @thin A.Type) -> A {
// CHECK: bb0(%0 : $KeyValuePairs<Any, Any>, %1 : $@thin A.Type):
// CHECK: unreachable , scope [[S2]]
// CHECK-LABEL: } // end sil function '$s18optimizer_pipeline1AVyACs13KeyValuePairsVyypypGcfC'
public struct A {
public init(_ pairs: KeyValuePairs<Any, Any>) {
Builtin.unreachable()
}
}
| apache-2.0 |
hexperimental/HxLib | HxLib/Classes/HxLocalStorage.swift | 1 | 2620 | //
// HxLocalStorage.swift
// Pods
//
// Created by Antonio Perez on 2017-04-18.
//
//
import Foundation
public class HxLocalStorage: AnyObject {
static var defaultValues:[String:AnyObject] = [String:AnyObject]()
public class func defaultValue(_ float:Float, forKey key:String) {
HxLocalStorage.defaultValues[key] = float as AnyObject
}
public class func defaultValue(_ int:Int, forKey key:String) {
HxLocalStorage.defaultValues[key] = int as AnyObject
}
public class func defaultValue(_ string:String, forKey key:String) {
HxLocalStorage.defaultValues[key] = string as AnyObject
}
public class func defaultValue(_ bool:Bool, forKey key:String) {
HxLocalStorage.defaultValues[key] = bool as AnyObject
}
public class func erase(_ key:String){
let userDefaults = UserDefaults.standard
userDefaults.set(nil, forKey: key)
userDefaults.synchronize()
}
public class func write(_ data:AnyObject? = nil, forKey key:String){
let userDefaults = UserDefaults.standard
userDefaults.set(data, forKey: key)
userDefaults.synchronize()
}
public class func write(_ float:Float, forKey key:String) {
HxLocalStorage.write(float as AnyObject, forKey:key)
}
public class func write(_ int:Int, forKey key:String) {
HxLocalStorage.write(int as AnyObject, forKey:key)
}
public class func write(_ string:String, forKey key:String) {
HxLocalStorage.write(string as AnyObject, forKey:key)
}
public class func write(_ bool:Bool, forKey key:String) {
HxLocalStorage.write(bool as AnyObject, forKey:key)
}
public class func read(_ keyStr:String)->AnyObject? {
let userDefaults = UserDefaults.standard
if let data:AnyObject = userDefaults.object(forKey: keyStr) as AnyObject? {
return data
}
if let defaultValue:AnyObject = HxLocalStorage.defaultValues[keyStr] as AnyObject? {
return defaultValue
}
return nil
}
public class func string(forKey str:String)->String? {
return HxLocalStorage.read(str) as? String
}
public class func stringValue(forKey str:String)->String {
return HxLocalStorage.read(str) as! String
}
public class func intValue(forKey str:String)->Int {
return HxLocalStorage.read(str) as! Int
}
public class func boolValue(forKey str:String)->Bool {
return HxLocalStorage.read(str) as! Bool
}
}
| mit |
royhsu/tiny-core | Sources/Core/Unique.swift | 1 | 259 | //
// Unique.swift
// TinyCore
//
// Created by Roy Hsu on 2018/9/22.
// Copyright © 2018 TinyWorld. All rights reserved.
//
// MARK: - Unique
public protocol Unique {
associatedtype Identifier: Hashable
var identifier: Identifier { get }
}
| mit |
ffxfiend/IGZQueueManager | IGZQueueManagerTests/StubNetworkHandler.swift | 1 | 1579 | //
// StubNetworkHandler.swift
// IGZQueueManager
//
// Created by Jeremiah Poisson on 10/4/16.
//
// Copyright (c) 2016 Jeremiah Poisson (http://miahpoisson.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import IGZQueueManager
class StubNetworkHandler : IGZNetworkHandlerProtocol {
func send(_ package: Package) {
guard let success = package.parameters["success"] as? Bool else {
package.failure(nil)
return
}
if (success) {
package.success(nil)
} else {
package.failure(nil)
}
}
}
| mit |
LittoCats/coffee-mobile | CoffeeMobile/Base/Utils/NSFundationExtension/CMNSThreadExtension.swift | 1 | 1573 | //
// NSThreadExtension.swift
// CoffeeMobile
//
// Created by 程巍巍 on 5/21/15.
// Copyright (c) 2015 Littocats. All rights reserved.
//
import Foundation
extension NSThread {
static func evalOnThread(thread: NSThread, waitUntilDon wait: Bool, closure: dispatch_block_t){
if thread == NSThread.currentThread() {
return closure()
}
Sync(closure: closure).evalSelector("excute", onThread: thread, waitUntilDone: wait)
}
private class Sync: NSObject {
private static var onceToken: dispatch_once_t = 0
override class func initialize(){
dispatch_once(&onceToken, { () -> Void in
var method = class_getInstanceMethod(NSObject.self, "evalSelector:onThread:withObject:waitUntilDone:modes:")
var _method = class_getInstanceMethod(NSObject.self, "performSelector:onThread:withObject:waitUntilDone:modes:")
method_exchangeImplementations(method, _method)
})
}
var closure: dispatch_block_t
init(closure: dispatch_block_t) {
self.closure = closure
}
@objc func excute() {
self.closure()
}
}
}
extension NSObject {
@objc private func evalSelector(selector: Selector, onThread thread: NSThread, withObject arg: AnyObject? = nil, waitUntilDone wait: Bool = true, modes array: [String] = [NSDefaultRunLoopMode]) {
evalSelector(selector, onThread: thread, withObject: arg, waitUntilDone: wait, modes: array)
}
} | apache-2.0 |
caicai0/ios_demo | load/thirdpart/SwiftSoup/ArrayExt.swift | 4 | 436 | //
// ArrayExt.swift
// SwifSoup
//
// Created by Nabil Chatbi on 05/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
extension Array where Element : Equatable {
func lastIndexOf(_ e: Element) -> Int {
for pos in (0..<self.count).reversed() {
let next = self[pos]
if (next == e) {
return pos
}
}
return -1
}
}
| mit |
iLandes/RSSunAndMoonCalc | RSSunAndMoonCalcDemo/AppDelegate.swift | 1 | 2193 | //
// AppDelegate.swift
// RSSunAndMoonCalcDemo
//
// Created by Sebastien REMY on 23/03/2017.
// Copyright © 2017 Sebastien REMY. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit |
karstengresch/rw_studies | RWBooks/RWBooks/ProfileViewController.swift | 1 | 2050 | //
// ViewController.swift
// RWBooks
//
// Created by Main Account on 5/13/15.
// Copyright (c) 2015 Razeware LLC. All rights reserved.
//
import UIKit
// http://www.materialpalette.com/light-blue/deep-orange
class ProfileViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate, UIViewControllerTransitioningDelegate {
@IBOutlet weak var avatarView: AvatarView!
@IBOutlet weak var topView: UIView!
@IBOutlet weak var followButton: UIButton!
@IBOutlet weak var collectionView: UICollectionView!
let books = Book.all
override func viewDidLoad() {
super.viewDidLoad()
followButton.layer.cornerRadius = CGRectGetHeight(followButton.bounds) / 2
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return books.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("BookCell", forIndexPath: indexPath) as! BookCell
let book = books[indexPath.row]
cell.imageView.image = book.cover
cell.imageView.layer.shadowRadius = 4
cell.imageView.layer.shadowOpacity = 0.5
cell.imageView.layer.shadowOffset = CGSize.zero
return cell
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
_ = self.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! BookCell
performSegueWithIdentifier("ShowBook", sender: indexPath)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let indexPath = sender as? NSIndexPath {
let destVC = segue.destinationViewController as! BookViewController
destVC.book = books[indexPath.row]
}
}
@IBAction func unwindToProfileView(sender: UIStoryboardSegue) {
}
}
| unlicense |
weareyipyip/SwiftStylable | Sources/SwiftStylable/Classes/Style/StylableComponents/STLayoutContraint.swift | 1 | 2884 | //
// STLayoutContraint.swift
// Pods-SwiftStylableExample
//
// Created by Rens Wijnmalen on 04/02/2019.
//
import UIKit
@IBDesignable open class STLayoutContraint: NSLayoutConstraint {
private var _dimension:String?
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: - Initializers & deinit
//
// -----------------------------------------------------------------------------------------------------------------------
public override init() {
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(STLayoutContraint.stylesDidUpdate(_:)), name: STYLES_DID_UPDATE, object: nil)
}
open override func awakeFromNib() {
super.awakeFromNib()
NotificationCenter.default.addObserver(self, selector: #selector(STLayoutContraint.stylesDidUpdate(_:)), name: STYLES_DID_UPDATE, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: - Computed properties
//
// -----------------------------------------------------------------------------------------------------------------------
@IBInspectable open var dimension:String? {
set {
self._dimension = newValue
self.updateDimension()
}
get {
return self._dimension
}
}
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: - Public methods
//
// -----------------------------------------------------------------------------------------------------------------------
public func applyDimension(_ name:String){
if self._dimension != name{
self._dimension = name
self.updateDimension()
}
}
public func updateDimension(){
if let dimensionName = self._dimension{
if let size = Styles.shared.dimensionNamed(dimensionName){
self.constant = size
} else {
print("WARNING: Dimension \(dimensionName) does not exist. (Is the dimension of type \"number\" in the plist 😉)")
}
}
}
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: - Internal methods
//
// -----------------------------------------------------------------------------------------------------------------------
@objc internal func stylesDidUpdate(_ notification:Notification) {
self.updateDimension()
}
}
| mit |
Draveness/RbSwift | RbSwiftTests/Array/Array+MutateSpec.swift | 1 | 4073 | //
// Array+MutateSpec.swift
// RbSwift
//
// Created by Draveness on 23/03/2017.
// Copyright © 2017 draveness. All rights reserved.
//
import Quick
import Nimble
import RbSwift
class ArrayMutateSpec: BaseSpec {
override func spec() {
describe(".clear") {
it("makes the array empty") {
var s = [1, 2, 3]
expect(s.clear()).to(equal([]))
}
}
describe(".delete") {
it("deletes and returns all the object if found") {
var arr1 = [1, 2, 3]
expect(arr1.delete(1)!).to(equal(1))
expect(arr1).to(equal([2, 3]))
var arr2 = [1, 2, 3, 1, 1]
expect(arr2.delete(1)!).to(equal(1))
expect(arr2).to(equal([2, 3]))
}
it("deletes and return the first object if flag all is false") {
var arr = [1, 2, 3, 1, 1]
expect(arr.delete(1, all: false)!).to(equal(1))
expect(arr).to(equal([2, 3, 1, 1]))
}
it("returns nil if found nothing") {
var arr1 = [1, 2, 3]
expect(arr1.delete(4)).to(beNil())
expect(arr1).to(equal([1, 2, 3]))
}
}
describe(".pop(num:)") {
it("returns the last element in array or nil") {
var arr = [1, 2, 3]
expect(arr.pop()).to(equal(3))
expect(arr).to(equal([1, 2]))
var arr1: [Int] = []
expect(arr1.pop()).to(beNil())
expect(arr1).to(equal([]))
var arr2 = [1, 2, 3]
expect(arr2.pop(2)).to(equal([2, 3]))
expect(arr2).to(equal([1]))
var arr3 = [1, 2, 3]
expect(arr3.pop(-1)).to(equal([]))
expect(arr3).to(equal([1, 2, 3]))
var arr4 = [1, 2, 3]
expect(arr4.pop(4)).to(equal([1, 2, 3]))
expect(arr4).to(equal([]))
}
}
describe(".push(objs:)") {
it("prepends objects to the front of self, moving other elements upwards.") {
var arr = [1, 2, 3]
expect(arr.push(1)).to(equal([1, 2, 3, 1]))
expect(arr).to(equal([1, 2, 3, 1]))
var arr1: [Int] = [1]
expect(arr1.push(1, 2, 3)).to(equal([1, 1, 2, 3]))
expect(arr1).to(equal([1, 1, 2, 3]))
}
}
describe(".shift(num:)") {
it("returns the first element in array or nil") {
var arr = [1, 2, 3]
expect(arr.shift()).to(equal(1))
expect(arr).to(equal([2, 3]))
var arr1: [Int] = []
expect(arr1.shift()).to(beNil())
expect(arr1).to(equal([]))
var arr2 = [1, 2, 3]
expect(arr2.shift(2)).to(equal([1, 2]))
expect(arr2).to(equal([3]))
var arr3 = [1, 2, 3]
expect(arr3.shift(-1)).to(equal([]))
expect(arr3).to(equal([1, 2, 3]))
var arr4 = [1, 2, 3]
expect(arr4.shift(4)).to(equal([1, 2, 3]))
expect(arr4).to(equal([]))
}
}
describe(".unshift(objs:)") {
it("prepends objects to the front of self, moving other elements upwards.") {
var arr = [1, 2, 3]
expect(arr.unshift(1)).to(equal([1, 1, 2, 3]))
expect(arr).to(equal([1, 1, 2, 3]))
var arr1: [Int] = [1, 2, 3]
expect(arr1.unshift(1, 2)).to(equal([1, 2, 1, 2, 3]))
expect(arr1).to(equal([1, 2, 1, 2, 3]))
}
}
}
}
| mit |
ahoppen/swift | test/stdlib/Mirror.swift | 4 | 62488 | //===--- Mirror.swift -----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
//
// RUN: if [ %target-runtime == "objc" ]; \
// RUN: then \
// RUN: %target-clang %S/Inputs/Mirror/Mirror.mm -c -o %t/Mirror.mm.o -g && \
// RUN: %target-build-swift %t/main.swift %S/Inputs/Mirror/MirrorOther.swift -I %S/Inputs/Mirror/ -Xlinker %t/Mirror.mm.o -o %t/Mirror; \
// RUN: else \
// RUN: %target-build-swift %t/main.swift %S/Inputs/Mirror/MirrorOther.swift -o %t/Mirror; \
// RUN: fi
// RUN: %target-codesign %t/Mirror
// RUN: %target-run %t/Mirror
// REQUIRES: executable_test
// REQUIRES: shell
// REQUIRES: reflection
import StdlibUnittest
var mirrors = TestSuite("Mirrors")
extension Mirror {
public var testDescription: String {
let nil_ = "nil"
return "[" +
children.lazy
.map { "\($0.0 ?? nil_): \(String(reflecting: $0.1))" }
.joined(separator: ", ")
+ "]"
}
}
mirrors.test("RandomAccessStructure") {
struct Eggs : CustomReflectable {
var customMirror: Mirror {
return Mirror(self, unlabeledChildren: ["aay", "bee", "cee"])
}
}
let x = Eggs().customMirror
expectEqual("[nil: \"aay\", nil: \"bee\", nil: \"cee\"]", x.testDescription)
}
let letters = "abcdefghijklmnopqrstuvwxyz "
func find(_ substring: String, within domain: String) -> String.Index? {
let domainCount = domain.count
let substringCount = substring.count
if (domainCount < substringCount) { return nil }
var sliceStart = domain.startIndex
var sliceEnd = domain.index(sliceStart, offsetBy: substringCount)
var i = 0
while true {
if domain[sliceStart..<sliceEnd] == substring {
return sliceStart
}
if i == domainCount - substringCount { break }
sliceStart = domain.index(after: sliceStart)
sliceEnd = domain.index(after: sliceEnd)
i += 1
}
return nil
}
mirrors.test("ForwardStructure") {
struct DoubleYou : CustomReflectable {
var customMirror: Mirror {
return Mirror(
self,
unlabeledChildren: Set(letters),
displayStyle: .`set`)
}
}
let w = DoubleYou().customMirror
expectEqual(.`set`, w.displayStyle)
expectEqual(letters.count, numericCast(w.children.count))
// Because we don't control the order of a Set, we need to do a
// fancy dance in order to validate the result.
let description = w.testDescription
for c in letters {
let expected = "nil: \"\(c)\""
expectNotNil(find(expected, within: description))
}
}
mirrors.test("BidirectionalStructure") {
struct Why : CustomReflectable {
var customMirror: Mirror {
return Mirror(
self,
unlabeledChildren: letters,
displayStyle: .collection)
}
}
// Test that the basics seem to work
let y = Why().customMirror
expectEqual(.`collection`, y.displayStyle)
let description = y.testDescription
expectEqual(
"[nil: \"a\", nil: \"b\", nil: \"c\", nil: \"",
description[description.startIndex..<description.firstIndex(of: "d")!])
}
mirrors.test("LabeledStructure") {
struct Zee : CustomReflectable, CustomStringConvertible {
var customMirror: Mirror {
return Mirror(self, children: ["bark": 1, "bite": 0])
}
var description: String { return "Zee" }
}
let z = Zee().customMirror
expectEqual("[bark: 1, bite: 0]", z.testDescription)
expectNil(z.displayStyle)
struct Zee2 : CustomReflectable {
var customMirror: Mirror {
return Mirror(
self, children: ["bark": 1, "bite": 0], displayStyle: .dictionary)
}
}
let z2 = Zee2().customMirror
expectEqual(.dictionary, z2.displayStyle)
expectEqual("[bark: 1, bite: 0]", z2.testDescription)
struct Heterogeny : CustomReflectable {
var customMirror: Mirror {
return Mirror(
self, children: ["bark": 1, "bite": Zee()])
}
}
let h = Heterogeny().customMirror
expectEqual("[bark: 1, bite: Zee]", h.testDescription)
}
mirrors.test("Legacy") {
let m = Mirror(reflecting: [1, 2, 3])
expectTrue(m.subjectType == [Int].self)
let x0: [Mirror.Child] = [
(label: nil, value: 1),
(label: nil, value: 2),
(label: nil, value: 3)
]
expectFalse(
zip(x0, m.children).contains {
$0.0.value as! Int != $0.1.value as! Int
})
class B { let bx: Int = 0 }
class D : B { let dx: Int = 1 }
let mb = Mirror(reflecting: B())
func expectBMirror(
_ mb: Mirror, stackTrace: SourceLocStack = SourceLocStack(),
file: String = #file, line: UInt = #line
) {
expectTrue(mb.subjectType == B.self,
stackTrace: stackTrace, file: file, line: line)
expectNil(
mb.superclassMirror,
stackTrace: stackTrace, file: file, line: line)
expectEqual(
1, mb.children.count,
stackTrace: stackTrace, file: file, line: line)
expectEqual(
"bx", mb.children.first?.label,
stackTrace: stackTrace, file: file, line: line)
expectEqual(
0, mb.children.first?.value as? Int,
stackTrace: stackTrace, file: file, line: line)
}
expectBMirror(mb)
// Ensure that the base class instance is properly filtered out of
// the child list
do {
let md = Mirror(reflecting: D())
expectTrue(md.subjectType == D.self)
expectEqual(1, md.children.count)
expectEqual("dx", md.children.first?.label)
expectEqual(1, md.children.first?.value as? Int)
expectNotNil(md.superclassMirror)
if let mb2 = md.superclassMirror { expectBMirror(mb2) }
}
do {
// Ensure that we reflect on the dynamic type of the subject
let md = Mirror(reflecting: D() as B)
expectTrue(md.subjectType == D.self)
expectEqual(1, md.children.count)
expectEqual("dx", md.children.first?.label)
expectEqual(1, md.children.first?.value as? Int)
expectNotNil(md.superclassMirror)
if let mb2 = md.superclassMirror { expectBMirror(mb2) }
}
}
//===----------------------------------------------------------------------===//
//===--- Class Support ----------------------------------------------------===//
class DullClass {}
mirrors.test("ClassReflection") {
expectEqual(.`class`, Mirror(reflecting: DullClass()).displayStyle)
}
mirrors.test("Class/Root/Uncustomized") {
class A { var a: Int = 1 }
let a = Mirror(reflecting: A())
expectTrue(a.subjectType == A.self)
expectNil(a.superclassMirror)
expectEqual(1, a.children.count)
expectEqual("a", a.children.first!.label)
}
//===--- Generated Superclass Mirrors -------------------------------------===//
mirrors.test("Class/Root/superclass:.generated") {
class B : CustomReflectable {
var b: String = "two"
var customMirror: Mirror {
return Mirror(
self, children: ["bee": b], ancestorRepresentation: .generated)
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
expectNil(b.superclassMirror)
expectEqual(1, b.children.count)
expectEqual("bee", b.children.first!.label)
expectEqual("two", b.children.first!.value as? String)
}
mirrors.test("class/Root/superclass:<default>") {
class C : CustomReflectable {
var c: UInt = 3
var customMirror: Mirror {
return Mirror(self, children: ["sea": c + 1])
}
}
let c = Mirror(reflecting: C())
expectTrue(c.subjectType == C.self)
expectNil(c.superclassMirror)
expectEqual(1, c.children.count)
expectEqual("sea", c.children.first!.label)
expectEqual(4, c.children.first!.value as? UInt)
}
mirrors.test("class/Plain/Plain") {
class A { var a: Int = 1 }
class B : A { var b: UInt = 42 }
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let bChild = expectNotNil(b.children.first) {
expectEqual("b", bChild.label)
expectEqual(42, bChild.value as? UInt)
}
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
if let aChild = expectNotNil(a.children.first) {
expectEqual("a", aChild.label)
expectEqual(1, aChild.value as? Int)
expectNil(a.superclassMirror)
}
}
}
mirrors.test("class/UncustomizedSuper/Synthesized/Implicit") {
class A { var a: Int = 1 }
class B : A, CustomReflectable {
var b: UInt = 42
var customMirror: Mirror {
return Mirror(self, children: ["bee": b])
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
expectEqual("a", a.children.first?.label)
expectNil(a.superclassMirror)
}
}
mirrors.test("class/UncustomizedSuper/Synthesized/Explicit") {
class A { var a: Int = 1 }
class B : A, CustomReflectable {
var b: UInt = 42
var customMirror: Mirror {
return Mirror(
self, children: ["bee": b], ancestorRepresentation: .generated)
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
expectEqual("a", a.children.first!.label)
expectNil(a.superclassMirror)
}
}
mirrors.test("class/CustomizedSuper/Synthesized") {
class A : CustomReflectable {
var a: Int = 1
var customMirror: Mirror {
return Mirror(self, children: ["aye": a])
}
}
class B : A {
var b: UInt = 42
// This is an unusual case: when writing override on a
// customMirror implementation you would typically want to pass
// ancestorRepresentation: .customized(super.customMirror) or, in
// rare cases, ancestorRepresentation: .Suppressed. However, it
// has an expected behavior, which we test here.
override var customMirror: Mirror {
return Mirror(self, children: ["bee": b])
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
expectEqual("a", a.children.first!.label)
expectNil(a.superclassMirror)
}
}
#if _runtime(_ObjC)
import Foundation
import MirrorObjC
//===--- ObjC Base Classes ------------------------------------------------===//
mirrors.test("class/ObjCPlain/Plain") {
class A : NSObject { var a: Int = 1 }
class B : A { var b: UInt = 42 }
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let bChild = expectNotNil(b.children.first) {
expectEqual("b", bChild.label)
expectEqual(42, bChild.value as? UInt)
}
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
if let aChild = expectNotNil(a.children.first) {
expectEqual("a", aChild.label)
expectEqual(1, aChild.value as? Int)
if let o = expectNotNil(a.superclassMirror) {
expectEqual("NSObject", String(reflecting: o.subjectType))
}
}
}
}
mirrors.test("class/ObjCUncustomizedSuper/Synthesized/Implicit") {
class A : NSObject { var a: Int = 1 }
class B : A, CustomReflectable {
var b: UInt = 42
var customMirror: Mirror {
return Mirror(self, children: ["bee": b])
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
expectEqual("a", a.children.first?.label)
if let o = expectNotNil(a.superclassMirror) {
expectTrue(o.subjectType == NSObject.self)
}
}
}
mirrors.test("class/ObjCUncustomizedSuper/Synthesized/Explicit") {
class A : NSObject { var a: Int = 1 }
class B : A, CustomReflectable {
var b: UInt = 42
var customMirror: Mirror {
return Mirror(
self, children: ["bee": b], ancestorRepresentation: .generated)
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
expectEqual("a", a.children.first!.label)
if let o = expectNotNil(a.superclassMirror) {
expectTrue(o.subjectType == NSObject.self)
}
}
}
mirrors.test("class/ObjCCustomizedSuper/Synthesized") {
class A : DateFormatter, CustomReflectable {
var a: Int = 1
var customMirror: Mirror {
return Mirror(self, children: ["aye": a])
}
}
class B : A {
var b: UInt = 42
// This is an unusual case: when writing override on a
// customMirror implementation you would typically want to pass
// ancestorRepresentation: .customized(super.customMirror) or, in
// rare cases, ancestorRepresentation: .Suppressed. However, it
// has an expected behavior, which we test here.
override var customMirror: Mirror {
return Mirror(self, children: ["bee": b])
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
expectEqual("a", a.children.first!.label)
if let d = expectNotNil(a.superclassMirror) {
expectTrue(d.subjectType == DateFormatter.self)
if let f = expectNotNil(d.superclassMirror) {
expectTrue(f.subjectType == Formatter.self)
if let o = expectNotNil(f.superclassMirror) {
expectTrue(o.subjectType == NSObject.self)
expectNil(o.superclassMirror)
}
}
}
}
}
mirrors.test("ObjC") {
// Some Foundation classes lie about their ivars, which would crash
// a mirror; make sure we are not automatically exposing ivars of
// Objective-C classes from the default mirror implementation.
expectEqual(0, Mirror(reflecting: HasIVars()).children.count)
}
// rdar://problem/39629937
@objc class ObjCClass : NSObject {
let value: Int
init(value: Int) { self.value = value }
override var description: String {
return "\(value)"
}
}
struct WrapObjCClassArray {
var array: [ObjCClass]
}
mirrors.test("struct/WrapNSArray") {
let nsArray: NSArray = [
ObjCClass(value: 1), ObjCClass(value: 2),
ObjCClass(value: 3), ObjCClass(value: 4)
]
let s = String(describing: WrapObjCClassArray(array: nsArray as! [ObjCClass]))
expectEqual("WrapObjCClassArray(array: [1, 2, 3, 4])", s)
}
#endif // _runtime(_ObjC)
//===--- Weak and Unowned References --------------------------------------===//
// Check that Mirror correctly reflects weak/unowned refs to both
// Swift and ObjC objects from Swift structs and classes.
protocol WeakUnownedTestsP1: AnyObject {
func f1() -> Int
}
protocol WeakUnownedTestsP2 {
func f2() -> String
}
class WeakUnownedSwiftClass: WeakUnownedTestsP1, WeakUnownedTestsP2 {
let tracker = LifetimeTracked(0)
func f1() -> Int { return 2 }
func f2() -> String { return "b" }
}
#if _runtime(_ObjC)
@objc class WeakUnownedObjCClass: NSObject, WeakUnownedTestsP1, WeakUnownedTestsP2 {
let tracker = LifetimeTracked(0)
func f1() -> Int { return 2 }
func f2() -> String { return "b" }
}
#endif
// The four tests below populate objects with different types
// but identical overall structure.
// This function is used by all four to verify that the resulting
// Mirror objects have the expected entries.
func verifyWeakUnownedReflection
<ExpectedClass: WeakUnownedTestsP1 & WeakUnownedTestsP2>
(_ m: Mirror, expectedClass: ExpectedClass.Type )
{
let i = m.children.makeIterator()
func verifyClassField(child: (label: String?, value: Any), name: String) {
expectEqual(child.label, name)
let v = child.value as? ExpectedClass
expectNotNil(v)
expectEqual(v!.f1(), 2)
}
func verifyExistentialField(child: (label: String?, value: Any), name: String) {
expectEqual(child.label, name)
expectNotNil(child.value)
// FIXME: These casts are currently broken (Dec 2019)
// Once they are fixed, enable additional checks:
//let vp1 = child.value as? WeakUnownedTestsP1
//expectNotNil(vp1)
//expectEqual(vp1!.f1(), 2)
//let vp2 = child.value as? WeakUnownedTestsP2
//expectNotNil(vp2)
//expectEqual(vp2!.f2(), "b")
let v = child.value as? ExpectedClass
expectNotNil(v)
expectEqual(v!.f1(), 2)
let m = Mirror(reflecting: v!)
expectEqual(m.displayStyle, .`class`)
// TODO: Find a way to verify that the existential wrapper carries
// the expected protocol witnesses. The current Swift runtime does
// a very good job of hiding this from users.
}
verifyClassField(child: i.next()!, name: "strong_class")
verifyExistentialField(child: i.next()!, name: "strong_existential")
verifyClassField(child: i.next()!, name: "weak_class")
verifyExistentialField(child: i.next()!, name: "weak_existential")
verifyClassField(child: i.next()!, name: "unowned_safe_class")
verifyExistentialField(child: i.next()!, name: "unowned_safe_existential")
verifyClassField(child: i.next()!, name: "unowned_unsafe_class")
verifyExistentialField(child: i.next()!, name: "unowned_unsafe_existential")
expectNil(i.next())
// The original bug report from SR-5289 crashed when the print() code
// attempted to reflect the contents of an unowned field.
// The tests above _should_ suffice to check this, but let's print everything
// anyway just to be sure.
for c in m.children {
print(c.label ?? "?", c.value)
}
}
#if _runtime(_ObjC)
// Related: SR-5289 reported a crash when using Mirror to inspect Swift
// class objects containing unowned pointers to Obj-C class objects.
mirrors.test("Weak and Unowned Obj-C refs in class (SR-5289)") {
class SwiftClassWithWeakAndUnowned {
var strong_class: WeakUnownedObjCClass
var strong_existential: WeakUnownedTestsP1 & WeakUnownedTestsP2
weak var weak_class: WeakUnownedObjCClass?
weak var weak_existential: (WeakUnownedTestsP1 & WeakUnownedTestsP2)?
unowned(safe) let unowned_safe_class: WeakUnownedObjCClass
unowned(safe) let unowned_safe_existential: WeakUnownedTestsP1 & WeakUnownedTestsP2
unowned(unsafe) let unowned_unsafe_class: WeakUnownedObjCClass
unowned(unsafe) let unowned_unsafe_existential: WeakUnownedTestsP1 & WeakUnownedTestsP2
init(_ objc: WeakUnownedObjCClass) {
self.strong_class = objc
self.strong_existential = objc
self.weak_class = objc
self.weak_existential = objc
self.unowned_safe_class = objc
self.unowned_safe_existential = objc
self.unowned_unsafe_class = objc
self.unowned_unsafe_existential = objc
}
}
if #available(SwiftStdlib 5.3, *) {
let objc = WeakUnownedObjCClass()
let classWithReferences = SwiftClassWithWeakAndUnowned(objc)
let m = Mirror(reflecting: classWithReferences)
expectEqual(m.displayStyle, .`class`)
expectEqual(m.description, "Mirror for SwiftClassWithWeakAndUnowned")
expectEqual(m.subjectType, SwiftClassWithWeakAndUnowned.self)
verifyWeakUnownedReflection(m, expectedClass: WeakUnownedObjCClass.self)
}
}
mirrors.test("Weak and Unowned Obj-C refs in struct") {
struct SwiftStructWithWeakAndUnowned {
var strong_class: WeakUnownedObjCClass
var strong_existential: WeakUnownedTestsP1 & WeakUnownedTestsP2
weak var weak_class: WeakUnownedObjCClass?
weak var weak_existential: (WeakUnownedTestsP1 & WeakUnownedTestsP2)?
unowned(safe) let unowned_safe_class: WeakUnownedObjCClass
unowned(safe) let unowned_safe_existential: WeakUnownedTestsP1 & WeakUnownedTestsP2
unowned(unsafe) let unowned_unsafe_class: WeakUnownedObjCClass
unowned(unsafe) let unowned_unsafe_existential: WeakUnownedTestsP1 & WeakUnownedTestsP2
init(_ objc: WeakUnownedObjCClass) {
self.strong_class = objc
self.strong_existential = objc
self.weak_class = objc
self.weak_existential = objc
self.unowned_safe_class = objc
self.unowned_safe_existential = objc
self.unowned_unsafe_class = objc
self.unowned_unsafe_existential = objc
}
}
if #available(SwiftStdlib 5.3, *) {
let objc = WeakUnownedObjCClass()
let structWithReferences = SwiftStructWithWeakAndUnowned(objc)
let m = Mirror(reflecting: structWithReferences)
expectEqual(m.displayStyle, .`struct`)
expectEqual(m.description, "Mirror for SwiftStructWithWeakAndUnowned")
expectEqual(m.subjectType, SwiftStructWithWeakAndUnowned.self)
verifyWeakUnownedReflection(m, expectedClass: WeakUnownedObjCClass.self)
}
}
#endif
mirrors.test("Weak and Unowned Swift refs in class") {
class SwiftClassWithWeakAndUnowned {
var strong_class: WeakUnownedSwiftClass
var strong_existential: WeakUnownedTestsP1 & WeakUnownedTestsP2
weak var weak_class: WeakUnownedSwiftClass?
weak var weak_existential: (WeakUnownedTestsP1 & WeakUnownedTestsP2)?
unowned(safe) let unowned_safe_class: WeakUnownedSwiftClass
unowned(safe) let unowned_safe_existential: (WeakUnownedTestsP1 & WeakUnownedTestsP2)
unowned(unsafe) let unowned_unsafe_class: WeakUnownedSwiftClass
unowned(unsafe) let unowned_unsafe_existential: (WeakUnownedTestsP1 & WeakUnownedTestsP2)
init(_ swift: WeakUnownedSwiftClass) {
self.strong_class = swift
self.strong_existential = swift
self.weak_class = swift
self.weak_existential = swift
self.unowned_safe_class = swift
self.unowned_safe_existential = swift
self.unowned_unsafe_class = swift
self.unowned_unsafe_existential = swift
}
}
if #available(SwiftStdlib 5.3, *) {
let swift = WeakUnownedSwiftClass()
let classWithReferences = SwiftClassWithWeakAndUnowned(swift)
let m = Mirror(reflecting: classWithReferences)
expectEqual(m.displayStyle, .`class`)
expectEqual(m.description, "Mirror for SwiftClassWithWeakAndUnowned")
expectEqual(m.subjectType, SwiftClassWithWeakAndUnowned.self)
verifyWeakUnownedReflection(m, expectedClass: WeakUnownedSwiftClass.self)
}
}
mirrors.test("Weak and Unowned Swift refs in struct") {
struct SwiftStructWithWeakAndUnowned {
var strong_class: WeakUnownedSwiftClass
var strong_existential: WeakUnownedTestsP1 & WeakUnownedTestsP2
weak var weak_class: WeakUnownedSwiftClass?
weak var weak_existential: (WeakUnownedTestsP1 & WeakUnownedTestsP2)?
unowned(safe) let unowned_safe_class: WeakUnownedSwiftClass
unowned(safe) let unowned_safe_existential: (WeakUnownedTestsP1 & WeakUnownedTestsP2)
unowned(unsafe) let unowned_unsafe_class: WeakUnownedSwiftClass
unowned(unsafe) let unowned_unsafe_existential: (WeakUnownedTestsP1 & WeakUnownedTestsP2)
init(_ swift: WeakUnownedSwiftClass) {
self.strong_class = swift
self.strong_existential = swift
self.weak_class = swift
self.weak_existential = swift
self.unowned_safe_class = swift
self.unowned_safe_existential = swift
self.unowned_unsafe_class = swift
self.unowned_unsafe_existential = swift
}
}
if #available(SwiftStdlib 5.3, *) {
let swift = WeakUnownedSwiftClass()
let structWithReferences = SwiftStructWithWeakAndUnowned(swift)
let m = Mirror(reflecting: structWithReferences)
expectEqual(m.displayStyle, .`struct`)
expectEqual(m.description, "Mirror for SwiftStructWithWeakAndUnowned")
expectEqual(m.subjectType, SwiftStructWithWeakAndUnowned.self)
verifyWeakUnownedReflection(m, expectedClass: WeakUnownedSwiftClass.self)
}
}
//===--- Suppressed Superclass Mirrors ------------------------------------===//
mirrors.test("Class/Root/NoSuperclassMirror") {
class B : CustomReflectable {
var b: String = "two"
var customMirror: Mirror {
return Mirror(
self, children: ["bee": b], ancestorRepresentation: .suppressed)
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
expectNil(b.superclassMirror)
expectEqual(1, b.children.count)
expectEqual("bee", b.children.first!.label)
}
mirrors.test("class/UncustomizedSuper/NoSuperclassMirror") {
class A { var a: Int = 1 }
class B : A, CustomReflectable {
var b: UInt = 42
var customMirror: Mirror {
return Mirror(
self, children: ["bee": b], ancestorRepresentation: .suppressed)
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
expectNil(b.superclassMirror)
}
mirrors.test("class/CustomizedSuper/NoSuperclassMirror") {
class A : CustomReflectable {
var a: Int = 1
var customMirror: Mirror {
return Mirror(self, children: ["aye": a])
}
}
class B : A {
var b: UInt = 42
override var customMirror: Mirror {
return Mirror(
self, children: ["bee": b], ancestorRepresentation: .suppressed)
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
expectNil(b.superclassMirror)
}
//===--- Override Superclass Mirrors --------------------------------------===//
mirrors.test("class/CustomizedSuper/SuperclassCustomMirror/Direct") {
class A : CustomReflectable {
var a: Int = 1
var customMirror: Mirror {
return Mirror(self, children: ["aye": a])
}
}
// B inherits A directly
class B : A {
var b: UInt = 42
override var customMirror: Mirror {
return Mirror(
self,
children: ["bee": b],
ancestorRepresentation: .customized({ super.customMirror }))
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
expectEqual("aye", a.children.first!.label)
expectNil(a.superclassMirror)
}
}
mirrors.test("class/CustomizedSuper/SuperclassCustomMirror/Indirect") {
class A : CustomReflectable {
var a: Int = 1
var customMirror: Mirror {
return Mirror(self, children: ["aye": a])
}
}
class X : A {}
class Y : X {}
// B inherits A indirectly through X and Y
class B : Y {
var b: UInt = 42
override var customMirror: Mirror {
return Mirror(
self,
children: ["bee": b],
ancestorRepresentation: .customized({ super.customMirror }))
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let y = expectNotNil(b.superclassMirror) {
expectTrue(y.subjectType == Y.self)
if let x = expectNotNil(y.superclassMirror) {
expectTrue(x.subjectType == X.self)
expectEqual(0, x.children.count)
if let a = expectNotNil(x.superclassMirror) {
expectTrue(a.subjectType == A.self)
if let aye = expectNotNil(a.children.first) {
expectEqual("aye", aye.label)
}
}
}
}
}
mirrors.test("class/CustomizedSuper/SuperclassCustomMirror/Indirect2") {
class A : CustomLeafReflectable {
var a: Int = 1
var customMirror: Mirror {
return Mirror(
self, children: ["aye": a])
}
}
class X : A {}
class Y : X {}
// B inherits A indirectly through X and Y
class B : Y {
var b: UInt = 42
override var customMirror: Mirror {
return Mirror(
self,
children: ["bee": b],
ancestorRepresentation: .customized({ super.customMirror }))
}
}
let b = Mirror(reflecting: B())
expectTrue(b.subjectType == B.self)
if let a = expectNotNil(b.superclassMirror) {
expectTrue(a.subjectType == A.self)
if let aye = expectNotNil(a.children.first) {
expectEqual("aye", aye.label)
}
}
}
mirrors.test("class/Cluster") {
class A : CustomLeafReflectable {
var a: Int = 1
var customMirror: Mirror {
return Mirror(
self, children: ["aye": a])
}
}
class X : A {}
class Y : X {}
let a = Mirror(reflecting: Y())
expectTrue(a.subjectType == A.self)
if let aye = expectNotNil(a.children.first) {
expectEqual("aye", aye.label)
}
}
//===--- Miscellaneous ----------------------------------------------------===//
//===----------------------------------------------------------------------===//
mirrors.test("Addressing") {
let m0 = Mirror(reflecting: [1, 2, 3])
expectEqual(1, m0.descendant(0) as? Int)
expectEqual(2, m0.descendant(1) as? Int)
expectEqual(3, m0.descendant(2) as? Int)
let m1 = Mirror(reflecting: (a: ["one", "two", "three"], 4))
let ott0 = m1.descendant(0) as? [String]
expectNotNil(ott0)
let ott1 = m1.descendant("a") as? [String]
expectNotNil(ott1)
if ott0 != nil && ott1 != nil {
expectEqualSequence(ott0!, ott1!)
}
expectEqual(4, m1.descendant(1) as? Int)
expectEqual(4, m1.descendant(".1") as? Int)
expectEqual("one", m1.descendant(0, 0) as? String)
expectEqual("two", m1.descendant(0, 1) as? String)
expectEqual("three", m1.descendant(0, 2) as? String)
expectEqual("one", m1.descendant("a", 0) as? String)
struct Zee : CustomReflectable {
var customMirror: Mirror {
return Mirror(self, children: ["bark": 1, "bite": 0])
}
}
let x = [
(a: ["one", "two", "three"], b: Zee()),
(a: ["five"], b: Zee()),
(a: [], b: Zee())]
let m = Mirror(reflecting: x)
let two = m.descendant(0, "a", 1)
expectEqual("two", two as? String)
expectEqual(1, m.descendant(1, 1, "bark") as? Int)
expectEqual(0, m.descendant(1, 1, "bite") as? Int)
expectNil(m.descendant(1, 1, "bork"))
}
#if !os(WASI)
// Trap tests aren't available on WASI.
mirrors.test("Invalid Path Type")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
struct X : MirrorPath {}
let m = Mirror(reflecting: [1, 2, 3])
expectEqual(1, m.descendant(0) as? Int)
expectCrashLater()
_ = m.descendant(X())
}
#endif
mirrors.test("PlaygroundQuickLook") {
// Customization works.
struct CustomQuickie : CustomPlaygroundQuickLookable {
var customPlaygroundQuickLook: PlaygroundQuickLook {
return .point(1.25, 42)
}
}
switch PlaygroundQuickLook(reflecting: CustomQuickie()) {
case .point(1.25, 42): break
default: expectTrue(false)
}
// PlaygroundQuickLook support from Legacy Mirrors works.
switch PlaygroundQuickLook(reflecting: true) {
case .bool(true): break
default: expectTrue(false)
}
// With no Legacy Mirror QuickLook support, we fall back to
// String(reflecting: ).
struct X {}
switch PlaygroundQuickLook(reflecting: X()) {
case .text(let text):
#if _runtime(_ObjC)
// FIXME: Enable if non-objc hasSuffix is implemented.
expectTrue(text.contains(").X"), text)
#endif
default:
expectTrue(false)
}
struct Y : CustomDebugStringConvertible {
var debugDescription: String { return "Why?" }
}
switch PlaygroundQuickLook(reflecting: Y()) {
case .text("Why?"): break
default: expectTrue(false)
}
}
class Parent {}
extension Parent : _DefaultCustomPlaygroundQuickLookable {
var _defaultCustomPlaygroundQuickLook: PlaygroundQuickLook {
return .text("base")
}
}
class Child : Parent { }
class FancyChild : Parent, CustomPlaygroundQuickLookable {
var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text("child")
}
}
mirrors.test("_DefaultCustomPlaygroundQuickLookable") {
// testing the workaround for custom quicklookables in subclasses
switch PlaygroundQuickLook(reflecting: Child()) {
case .text("base"): break
default: expectUnreachable("Base custom quicklookable was expected")
}
switch PlaygroundQuickLook(reflecting: FancyChild()) {
case .text("child"): break
default: expectUnreachable("FancyChild custom quicklookable was expected")
}
}
mirrors.test("String.init") {
expectEqual("42", String(42))
expectEqual("42", String("42"))
expectEqual("42", String(reflecting: 42))
expectEqual("\"42\"", String(reflecting: "42"))
}
//===--- Structs ----------------------------------------------------------===//
//===----------------------------------------------------------------------===//
struct StructWithDefaultMirror {
let s: String
init (_ s: String) {
self.s = s
}
}
mirrors.test("Struct/NonGeneric/DefaultMirror") {
do {
var output = ""
dump(StructWithDefaultMirror("123"), to: &output)
expectEqual("▿ Mirror.StructWithDefaultMirror\n - s: \"123\"\n", output)
}
do {
// Build a String around an interpolation as a way of smoke-testing that
// the internal _Mirror implementation gets memory management right.
var output = ""
dump(StructWithDefaultMirror("\(456)"), to: &output)
expectEqual("▿ Mirror.StructWithDefaultMirror\n - s: \"456\"\n", output)
}
expectEqual(
.`struct`,
Mirror(reflecting: StructWithDefaultMirror("")).displayStyle)
}
struct GenericStructWithDefaultMirror<T, U> {
let first: T
let second: U
}
mirrors.test("Struct/Generic/DefaultMirror") {
do {
let value = GenericStructWithDefaultMirror<Int, [Any?]>(
first: 123,
second: ["abc", 456, 789.25])
var output = ""
dump(value, to: &output)
let expected =
"▿ Mirror.GenericStructWithDefaultMirror<Swift.Int, Swift.Array<Swift.Optional<Any>>>\n" +
" - first: 123\n" +
" ▿ second: 3 elements\n" +
" ▿ Optional(\"abc\")\n" +
" - some: \"abc\"\n" +
" ▿ Optional(456)\n" +
" - some: 456\n" +
" ▿ Optional(789.25)\n" +
" - some: 789.25\n"
expectEqual(expected, output)
}
}
//===--- Enums ------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
enum NoPayloadEnumWithDefaultMirror {
case A, ß
}
mirrors.test("Enum/NoPayload/DefaultMirror") {
do {
let value: [NoPayloadEnumWithDefaultMirror] =
[.A, .ß]
var output = ""
dump(value, to: &output)
let expected =
"▿ 2 elements\n" +
" - Mirror.NoPayloadEnumWithDefaultMirror.A\n" +
" - Mirror.NoPayloadEnumWithDefaultMirror.ß\n"
expectEqual(expected, output)
}
}
enum SingletonNonGenericEnumWithDefaultMirror {
case OnlyOne(Int)
}
mirrors.test("Enum/SingletonNonGeneric/DefaultMirror") {
do {
let value = SingletonNonGenericEnumWithDefaultMirror.OnlyOne(5)
var output = ""
dump(value, to: &output)
let expected =
"▿ Mirror.SingletonNonGenericEnumWithDefaultMirror.OnlyOne\n" +
" - OnlyOne: 5\n"
expectEqual(expected, output)
}
}
enum ZeroSizedEnumWithDefaultMirror {
case π
}
enum SingletonZeroSizedEnumWithDefaultMirror {
case wrap(ZeroSizedEnumWithDefaultMirror)
}
mirrors.test("Enum/SingletonZeroSizedEnumWithDefaultMirror/DefaultMirror") {
do {
let value = SingletonZeroSizedEnumWithDefaultMirror.wrap(.π)
var output = ""
dump(value, to: &output)
let expected =
"▿ Mirror.SingletonZeroSizedEnumWithDefaultMirror.wrap\n" +
" - wrap: Mirror.ZeroSizedEnumWithDefaultMirror.π\n"
expectEqual(expected, output)
}
}
enum SingletonGenericEnumWithDefaultMirror<T> {
case OnlyOne(T)
}
mirrors.test("Enum/SingletonGeneric/DefaultMirror") {
do {
let value = SingletonGenericEnumWithDefaultMirror.OnlyOne("IIfx")
var output = ""
dump(value, to: &output)
let expected =
"▿ Mirror.SingletonGenericEnumWithDefaultMirror<Swift.String>.OnlyOne\n" +
" - OnlyOne: \"IIfx\"\n"
expectEqual(expected, output)
}
expectEqual(0, LifetimeTracked.instances)
do {
let value = SingletonGenericEnumWithDefaultMirror.OnlyOne(
LifetimeTracked(0))
expectEqual(1, LifetimeTracked.instances)
var output = ""
dump(value, to: &output)
}
expectEqual(0, LifetimeTracked.instances)
}
enum SinglePayloadNonGenericEnumWithDefaultMirror {
case Cat
case Dog
case Volleyball(String, Int)
}
mirrors.test("Enum/SinglePayloadNonGeneric/DefaultMirror") {
do {
let value: [SinglePayloadNonGenericEnumWithDefaultMirror] =
[.Cat,
.Dog,
.Volleyball("Wilson", 2000)]
var output = ""
dump(value, to: &output)
let expected =
"▿ 3 elements\n" +
" - Mirror.SinglePayloadNonGenericEnumWithDefaultMirror.Cat\n" +
" - Mirror.SinglePayloadNonGenericEnumWithDefaultMirror.Dog\n" +
" ▿ Mirror.SinglePayloadNonGenericEnumWithDefaultMirror.Volleyball\n" +
" ▿ Volleyball: (2 elements)\n" +
" - .0: \"Wilson\"\n" +
" - .1: 2000\n"
expectEqual(expected, output)
}
}
enum SinglePayloadGenericEnumWithDefaultMirror<T, U> {
case Well
case Faucet
case Pipe(T, U)
}
mirrors.test("Enum/SinglePayloadGeneric/DefaultMirror") {
do {
let value: [SinglePayloadGenericEnumWithDefaultMirror<Int, [Int]>] =
[.Well,
.Faucet,
.Pipe(408, [415])]
var output = ""
dump(value, to: &output)
let expected =
"▿ 3 elements\n" +
" - Mirror.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Well\n" +
" - Mirror.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Faucet\n" +
" ▿ Mirror.SinglePayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.Array<Swift.Int>>.Pipe\n" +
" ▿ Pipe: (2 elements)\n" +
" - .0: 408\n" +
" ▿ .1: 1 element\n" +
" - 415\n"
expectEqual(expected, output)
}
}
enum MultiPayloadTagBitsNonGenericEnumWithDefaultMirror {
case Plus
case SE30
case Classic(mhz: Int)
case Performa(model: Int)
}
mirrors.test("Enum/MultiPayloadTagBitsNonGeneric/DefaultMirror") {
do {
let value: [MultiPayloadTagBitsNonGenericEnumWithDefaultMirror] =
[.Plus,
.SE30,
.Classic(mhz: 16),
.Performa(model: 220)]
var output = ""
dump(value, to: &output)
let expected =
"▿ 4 elements\n" +
" - Mirror.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Plus\n" +
" - Mirror.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.SE30\n" +
" ▿ Mirror.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Classic\n" +
" ▿ Classic: (1 element)\n" +
" - mhz: 16\n" +
" ▿ Mirror.MultiPayloadTagBitsNonGenericEnumWithDefaultMirror.Performa\n" +
" ▿ Performa: (1 element)\n" +
" - model: 220\n"
expectEqual(expected, output)
}
}
class Floppy {
let capacity: Int
init(capacity: Int) { self.capacity = capacity }
}
class CDROM {
let capacity: Int
init(capacity: Int) { self.capacity = capacity }
}
enum MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror {
case MacWrite
case MacPaint
case FileMaker
case ClarisWorks(floppy: Floppy)
case HyperCard(cdrom: CDROM)
}
mirrors.test("Enum/MultiPayloadSpareBitsNonGeneric/DefaultMirror") {
do {
let value: [MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror] =
[.MacWrite,
.MacPaint,
.FileMaker,
.ClarisWorks(floppy: Floppy(capacity: 800)),
.HyperCard(cdrom: CDROM(capacity: 600))]
var output = ""
dump(value, to: &output)
let expected =
"▿ 5 elements\n" +
" - Mirror.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.MacWrite\n" +
" - Mirror.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.MacPaint\n" +
" - Mirror.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.FileMaker\n" +
" ▿ Mirror.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.ClarisWorks\n" +
" ▿ ClarisWorks: (1 element)\n" +
" ▿ floppy: Mirror.Floppy #0\n" +
" - capacity: 800\n" +
" ▿ Mirror.MultiPayloadSpareBitsNonGenericEnumWithDefaultMirror.HyperCard\n" +
" ▿ HyperCard: (1 element)\n" +
" ▿ cdrom: Mirror.CDROM #1\n" +
" - capacity: 600\n"
expectEqual(expected, output)
}
}
enum MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror {
case MacWrite
case MacPaint
case FileMaker
case ClarisWorks(floppy: Bool)
case HyperCard(cdrom: Bool)
}
mirrors.test("Enum/MultiPayloadTagBitsSmallNonGeneric/DefaultMirror") {
do {
let value: [MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror] =
[.MacWrite,
.MacPaint,
.FileMaker,
.ClarisWorks(floppy: true),
.HyperCard(cdrom: false)]
var output = ""
dump(value, to: &output)
let expected =
"▿ 5 elements\n" +
" - Mirror.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.MacWrite\n" +
" - Mirror.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.MacPaint\n" +
" - Mirror.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.FileMaker\n" +
" ▿ Mirror.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.ClarisWorks\n" +
" ▿ ClarisWorks: (1 element)\n" +
" - floppy: true\n" +
" ▿ Mirror.MultiPayloadTagBitsSmallNonGenericEnumWithDefaultMirror.HyperCard\n" +
" ▿ HyperCard: (1 element)\n" +
" - cdrom: false\n"
expectEqual(expected, output)
}
}
enum MultiPayloadGenericEnumWithDefaultMirror<T, U> {
case IIe
case IIgs
case Centris(ram: T)
case Quadra(hdd: U)
case PowerBook170
case PowerBookDuo220
}
mirrors.test("Enum/MultiPayloadGeneric/DefaultMirror") {
do {
let value: [MultiPayloadGenericEnumWithDefaultMirror<Int, String>] =
[.IIe,
.IIgs,
.Centris(ram: 4096),
.Quadra(hdd: "160MB"),
.PowerBook170,
.PowerBookDuo220]
var output = ""
dump(value, to: &output)
let expected =
"▿ 6 elements\n" +
" - Mirror.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.IIe\n" +
" - Mirror.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.IIgs\n" +
" ▿ Mirror.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.Centris\n" +
" ▿ Centris: (1 element)\n" +
" - ram: 4096\n" +
" ▿ Mirror.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.Quadra\n" +
" ▿ Quadra: (1 element)\n" +
" - hdd: \"160MB\"\n" +
" - Mirror.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.PowerBook170\n" +
" - Mirror.MultiPayloadGenericEnumWithDefaultMirror<Swift.Int, Swift.String>.PowerBookDuo220\n"
expectEqual(expected, output)
}
expectEqual(0, LifetimeTracked.instances)
do {
let value = MultiPayloadGenericEnumWithDefaultMirror<LifetimeTracked,
LifetimeTracked>
.Quadra(hdd: LifetimeTracked(0))
expectEqual(1, LifetimeTracked.instances)
var output = ""
dump(value, to: &output)
}
expectEqual(0, LifetimeTracked.instances)
}
enum Foo<T> {
indirect case Foo(Int)
case Bar(T)
}
enum List<T> {
case Nil
indirect case Cons(first: T, rest: List<T>)
}
mirrors.test("Enum/IndirectGeneric/DefaultMirror") {
let x = Foo<String>.Foo(22)
let y = Foo<String>.Bar("twenty-two")
expectEqual("\(x)", "Foo(22)")
expectEqual("\(y)", "Bar(\"twenty-two\")")
let list = List.Cons(first: 0, rest: .Cons(first: 1, rest: .Nil))
expectEqual("Cons(first: 0, rest: Mirror.List<Swift.Int>.Cons(first: 1, rest: Mirror.List<Swift.Int>.Nil))",
"\(list)")
}
enum MyError: Error {
case myFirstError(LifetimeTracked)
}
mirrors.test("Enum/CaseName/Error") {
// Just make sure this doesn't leak.
let e: Error = MyError.myFirstError(LifetimeTracked(0))
_ = String(describing: e)
}
class Brilliant : CustomReflectable {
let first: Int
let second: String
init(_ fst: Int, _ snd: String) {
self.first = fst
self.second = snd
}
var customMirror: Mirror {
return Mirror(self, children: ["first": first, "second": second, "self": self])
}
}
//===--- Custom mirrors ---------------------------------------------------===//
//===----------------------------------------------------------------------===//
/// Subclasses inherit their parents' custom mirrors.
class Irradiant : Brilliant {
init() {
super.init(400, "")
}
}
mirrors.test("CustomMirror") {
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output)
let expected =
"▿ Mirror.Brilliant #0\n" +
" - first: 123\n" +
" - second: \"four five six\"\n" +
" ▿ self: Mirror.Brilliant #0\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output, maxDepth: 0)
expectEqual("▹ Mirror.Brilliant #0\n", output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output, maxItems: 3)
let expected =
"▿ Mirror.Brilliant #0\n" +
" - first: 123\n" +
" - second: \"four five six\"\n" +
" (1 more child)\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output, maxItems: 2)
let expected =
"▿ Mirror.Brilliant #0\n" +
" - first: 123\n" +
" (2 more children)\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Brilliant(123, "four five six"), to: &output, maxItems: 1)
let expected =
"▿ Mirror.Brilliant #0\n" +
" (3 children)\n"
expectEqual(expected, output)
}
}
mirrors.test("CustomMirrorIsInherited") {
do {
var output = ""
dump(Irradiant(), to: &output)
let expected =
"▿ Mirror.Brilliant #0\n" +
" - first: 400\n" +
" - second: \"\"\n" +
" ▿ self: Mirror.Brilliant #0\n"
expectEqual(expected, output)
}
}
//===--- Metatypes --------------------------------------------------------===//
//===----------------------------------------------------------------------===//
protocol SomeNativeProto {}
extension Int: SomeNativeProto {}
class SomeClass {}
mirrors.test("MetatypeMirror") {
do {
var output = ""
let concreteMetatype = Int.self
dump(concreteMetatype, to: &output)
let expectedInt = "- Swift.Int #0\n"
expectEqual(expectedInt, output)
let anyMetatype: Any.Type = Int.self
output = ""
dump(anyMetatype, to: &output)
expectEqual(expectedInt, output)
let nativeProtocolMetatype: SomeNativeProto.Type = Int.self
output = ""
dump(nativeProtocolMetatype, to: &output)
expectEqual(expectedInt, output)
let concreteClassMetatype = SomeClass.self
let expectedSomeClass = "- Mirror.SomeClass #0\n"
output = ""
dump(concreteClassMetatype, to: &output)
expectEqual(expectedSomeClass, output)
let nativeProtocolConcreteMetatype = SomeNativeProto.self
let expectedNativeProtocolConcrete = "- Mirror.SomeNativeProto #0\n"
output = ""
dump(nativeProtocolConcreteMetatype, to: &output)
expectEqual(expectedNativeProtocolConcrete, output)
}
}
//===--- Tuples -----------------------------------------------------------===//
//===----------------------------------------------------------------------===//
mirrors.test("TupleMirror") {
do {
var output = ""
let tuple =
(Brilliant(384, "seven six eight"), StructWithDefaultMirror("nine"))
dump(tuple, to: &output)
let expected =
"▿ (2 elements)\n" +
" ▿ .0: Mirror.Brilliant #0\n" +
" - first: 384\n" +
" - second: \"seven six eight\"\n" +
" ▿ self: Mirror.Brilliant #0\n" +
" ▿ .1: Mirror.StructWithDefaultMirror\n" +
" - s: \"nine\"\n"
expectEqual(expected, output)
expectEqual(.tuple, Mirror(reflecting: tuple).displayStyle)
}
do {
// A tuple of stdlib types with mirrors.
var output = ""
let tuple = (1, 2.5, false, "three")
dump(tuple, to: &output)
let expected =
"▿ (4 elements)\n" +
" - .0: 1\n" +
" - .1: 2.5\n" +
" - .2: false\n" +
" - .3: \"three\"\n"
expectEqual(expected, output)
}
do {
// A nested tuple.
var output = ""
let tuple = (1, ("Hello", "World"))
dump(tuple, to: &output)
let expected =
"▿ (2 elements)\n" +
" - .0: 1\n" +
" ▿ .1: (2 elements)\n" +
" - .0: \"Hello\"\n" +
" - .1: \"World\"\n"
expectEqual(expected, output)
}
}
//===--- Standard library types -------------------------------------------===//
//===----------------------------------------------------------------------===//
mirrors.test("String/Mirror") {
do {
var output = ""
dump("", to: &output)
let expected =
"- \"\"\n"
expectEqual(expected, output)
}
do {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}", to: &output)
let expected =
"- \"\u{61}\u{304b}\u{3099}\u{1f425}\"\n"
expectEqual(expected, output)
}
}
mirrors.test("String.UTF8View/Mirror") {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
var output = ""
dump("\u{61}\u{304b}\u{3099}".utf8, to: &output)
let expected =
"▿ UTF8View(\"\u{61}\u{304b}\u{3099}\")\n" +
" - 97\n" +
" - 227\n" +
" - 129\n" +
" - 139\n" +
" - 227\n" +
" - 130\n" +
" - 153\n"
expectEqual(expected, output)
}
mirrors.test("String.UTF16View/Mirror") {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}".utf16, to: &output)
let expected =
"▿ StringUTF16(\"\u{61}\u{304b}\u{3099}\u{1f425}\")\n" +
" - 97\n" +
" - 12363\n" +
" - 12441\n" +
" - 55357\n" +
" - 56357\n"
expectEqual(expected, output)
}
mirrors.test("String.UnicodeScalarView/Mirror") {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}".unicodeScalars, to: &output)
let expected =
"▿ StringUnicodeScalarView(\"\u{61}\u{304b}\u{3099}\u{1f425}\")\n" +
" - \"\u{61}\"\n" +
" - \"\\u{304B}\"\n" +
" - \"\\u{3099}\"\n" +
" - \"\\u{0001F425}\"\n"
expectEqual(expected, output)
}
mirrors.test("Character/Mirror") {
do {
// U+0061 LATIN SMALL LETTER A
let input: Character = "\u{61}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\u{61}\"\n"
expectEqual(expected, output)
}
do {
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
let input: Character = "\u{304b}\u{3099}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\u{304b}\u{3099}\"\n"
expectEqual(expected, output)
}
do {
// U+1F425 FRONT-FACING BABY CHICK
let input: Character = "\u{1f425}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\u{1f425}\"\n"
expectEqual(expected, output)
}
}
mirrors.test("UnicodeScalar") {
do {
// U+0061 LATIN SMALL LETTER A
let input: UnicodeScalar = "\u{61}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\u{61}\"\n"
expectEqual(expected, output)
}
do {
// U+304B HIRAGANA LETTER KA
let input: UnicodeScalar = "\u{304b}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\\u{304B}\"\n"
expectEqual(expected, output)
}
do {
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
let input: UnicodeScalar = "\u{3099}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\\u{3099}\"\n"
expectEqual(expected, output)
}
do {
// U+1F425 FRONT-FACING BABY CHICK
let input: UnicodeScalar = "\u{1f425}"
var output = ""
dump(input, to: &output)
let expected =
"- \"\\u{0001F425}\"\n"
expectEqual(expected, output)
}
}
mirrors.test("Bool") {
do {
var output = ""
dump(false, to: &output)
let expected =
"- false\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(true, to: &output)
let expected =
"- true\n"
expectEqual(expected, output)
}
}
// FIXME: these tests should cover Float80.
// FIXME: these tests should be automatically generated from the list of
// available floating point types.
mirrors.test("Float") {
do {
var output = ""
dump(Float.nan, to: &output)
let expected =
"- nan\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Float.infinity, to: &output)
let expected =
"- inf\n"
expectEqual(expected, output)
}
do {
let input: Float = 42.125
var output = ""
dump(input, to: &output)
let expected =
"- 42.125\n"
expectEqual(expected, output)
}
}
mirrors.test("Double") {
do {
var output = ""
dump(Double.nan, to: &output)
let expected =
"- nan\n"
expectEqual(expected, output)
}
do {
var output = ""
dump(Double.infinity, to: &output)
let expected =
"- inf\n"
expectEqual(expected, output)
}
do {
let input: Double = 42.125
var output = ""
dump(input, to: &output)
let expected =
"- 42.125\n"
expectEqual(expected, output)
}
}
mirrors.test("StaticString/Mirror") {
do {
var output = ""
dump("" as StaticString, to: &output)
let expected =
"- \"\"\n"
expectEqual(expected, output)
}
do {
// U+0061 LATIN SMALL LETTER A
// U+304B HIRAGANA LETTER KA
// U+3099 COMBINING KATAKANA-HIRAGANA VOICED SOUND MARK
// U+1F425 FRONT-FACING BABY CHICK
var output = ""
dump("\u{61}\u{304b}\u{3099}\u{1f425}" as StaticString, to: &output)
let expected =
"- \"\u{61}\u{304b}\u{3099}\u{1f425}\"\n"
expectEqual(expected, output)
}
}
mirrors.test("DictionaryIterator/Mirror") {
let d: [MinimalHashableValue : OpaqueValue<Int>] =
[ MinimalHashableValue(0) : OpaqueValue(0) ]
var output = ""
dump(d.makeIterator(), to: &output)
let expected =
"- Swift.Dictionary<StdlibUnittest.MinimalHashableValue, StdlibUnittest.OpaqueValue<Swift.Int>>.Iterator\n"
expectEqual(expected, output)
}
mirrors.test("SetIterator/Mirror") {
let s: Set<MinimalHashableValue> = [ MinimalHashableValue(0)]
var output = ""
dump(s.makeIterator(), to: &output)
let expected =
"- Swift.Set<StdlibUnittest.MinimalHashableValue>.Iterator\n"
expectEqual(expected, output)
}
//===--- Regressions ------------------------------------------------------===//
//===----------------------------------------------------------------------===//
// A struct type and class type whose NominalTypeDescriptor.FieldNames
// data is exactly eight bytes long. FieldNames data of exactly
// 4 or 8 or 16 bytes was once miscompiled on arm64.
struct EightByteFieldNamesStruct {
let abcdef = 42
}
class EightByteFieldNamesClass {
let abcdef = 42
}
mirrors.test("FieldNamesBug") {
do {
let expected =
"▿ Mirror.EightByteFieldNamesStruct\n" +
" - abcdef: 42\n"
var output = ""
dump(EightByteFieldNamesStruct(), to: &output)
expectEqual(expected, output)
}
do {
let expected =
"▿ Mirror.EightByteFieldNamesClass #0\n" +
" - abcdef: 42\n"
var output = ""
dump(EightByteFieldNamesClass(), to: &output)
expectEqual(expected, output)
}
}
mirrors.test("MirrorMirror") {
let object = 1
let mirror = Mirror(reflecting: object)
let mirrorMirror = Mirror(reflecting: mirror)
expectEqual(0, mirrorMirror.children.count)
}
mirrors.test("OpaquePointer/null") {
// Don't crash on null pointers. rdar://problem/19708338
let pointer: OpaquePointer? = nil
let mirror = Mirror(reflecting: pointer as Any)
expectEqual(0, mirror.children.count)
}
struct a<b> {
enum c{}
}
class d {}
struct e<f> {
var constraints: [Int: a<f>.c] = [:]
}
mirrors.test("GenericNestedTypeField") {
let x = e<d>()
expectTrue(type(of: Mirror(reflecting: x).children.first!.value)
== [Int: a<d>.c].self)
}
extension OtherOuter {
struct Inner {}
}
extension OtherOuterGeneric {
struct Inner<U> {}
}
mirrors.test("SymbolicReferenceInsideType") {
let s = OtherStruct(a: OtherOuter.Inner(),
b: OtherOuterGeneric<Int>.Inner<String>())
var output = ""
dump(s, to: &output)
let expected =
"▿ Mirror.OtherStruct\n" +
" - a: Mirror.OtherOuter.Inner\n" +
" - b: Mirror.OtherOuterGeneric<Swift.Int>.Inner<Swift.String>\n"
expectEqual(expected, output)
}
protocol P1 { }
protocol P2 { }
protocol P3 { }
struct ConformsToP1: P1 { }
struct ConformsToP2: P2 { }
struct ConformsToP3: P3 { }
struct OuterTwoParams<T: P1, U: P2> {}
struct ConformsToP1AndP2 : P1, P2 { }
extension OuterTwoParams where U == T {
struct InnerEqualParams<V: P3> {
var x: T
var y: U
var z: V
}
}
mirrors.test("GenericNestedWithSameTypeConstraints") {
let value = OuterTwoParams.InnerEqualParams(x: ConformsToP1AndP2(),
y: ConformsToP1AndP2(),
z: ConformsToP3())
var output = ""
dump(value, to: &output)
let expected =
"▿ (extension in Mirror):Mirror.OuterTwoParams<Mirror.ConformsToP1AndP2, Mirror.ConformsToP1AndP2>.InnerEqualParams<Mirror.ConformsToP3>\n" +
" - x: Mirror.ConformsToP1AndP2\n" +
" - y: Mirror.ConformsToP1AndP2\n" +
" - z: Mirror.ConformsToP3\n"
expectEqual(expected, output)
}
@_alignment(16) struct CustomAlignment {
var x: Int
var y: Int
}
mirrors.test("CustomAlignment") {
let value = CustomAlignment(x: 123, y: 321)
var output = ""
dump(value, to: &output)
let expected =
"▿ Mirror.CustomAlignment\n" +
" - x: 123\n" +
" - y: 321\n"
expectEqual(expected, output)
}
protocol STSTagProtocol {}
struct STSOuter : STSTagProtocol {}
enum STSContainer<T : STSTagProtocol> {
class Superclass {}
class Subclass<U>: Superclass where T == STSOuter {
class ExtraNested: Superclass {}
}
class GenericSuperclass<U> {}
class Subclass2<U>: GenericSuperclass<U> where T == STSOuter {}
class Subclass3<U: Collection>: Superclass where T == U.Element {}
class MoreNesting<X> {
class Subclass<U>: Superclass where T == STSOuter {}
}
struct Fields<U> where T == STSOuter {
var x: T?
var y: U?
}
enum Cases<U> where T == STSOuter {
case a(T)
case b(U)
}
}
// A new type with an easily-recognizable, easily-strippable suffix character.
enum STSContainer℠<T : STSTagProtocol> {
class Superclass {}
class GenericSuperclass<U> {}
}
extension STSContainer℠ where T == STSOuter {
class Subclass<U>: Superclass {
class ExtraNested: Superclass {}
}
class Subclass2<U>: GenericSuperclass<U> {}
class MoreNesting<X> {
class Subclass<U>: Superclass {}
}
struct Fields<U> {
var x: T?
var y: U?
}
enum Cases<U> {
case a(T)
case b(U)
}
}
var sameTypeSuite = TestSuite("Mirrors.SameTypeConstraints")
func testSTSDump<RegularValue, ExtensionValue>(
_ regular: RegularValue,
_ ext: ExtensionValue,
_ expected: String
) {
var output = ""
dump(regular, to: &output)
expectEqual(expected, output)
func clean(_ dumpOutput: String) -> String {
// This isn't efficient but it doesn't have to be.
var result = dumpOutput
result.removeAll { $0 == "℠" }
if let openParenIndex = result.firstIndex(of: "(") {
if result[openParenIndex...].hasPrefix("(extension in Mirror):") {
let colonIndex = result[openParenIndex...].firstIndex(of: ":")!
result.removeSubrange(openParenIndex...colonIndex)
}
}
return result
}
var extensionOutput = ""
dump(ext, to: &extensionOutput)
expectEqual(expected, clean(extensionOutput))
}
func testSTSDump<RegularValue>(_ regular: RegularValue, _ expected: String) {
var output = ""
dump(regular, to: &output)
expectEqual(expected, output)
}
if #available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *) {
sameTypeSuite.test("Subclass") {
testSTSDump(STSContainer.Subclass<Int>(),
STSContainer℠.Subclass<Int>(),
"""
- Mirror.STSContainer<Mirror.STSOuter>.Subclass<Swift.Int> #0
- super: Mirror.STSContainer<Mirror.STSOuter>.Superclass\n
""")
testSTSDump(STSContainer.Subclass2<Int>(),
STSContainer℠.Subclass2<Int>(),
"""
- Mirror.STSContainer<Mirror.STSOuter>.Subclass2<Swift.Int> #0
- super: Mirror.STSContainer<Mirror.STSOuter>.GenericSuperclass<Swift.Int>\n
""")
testSTSDump(STSContainer.Subclass3<[STSOuter]>(),
"""
- Mirror.STSContainer<Mirror.STSOuter>.Subclass3<Swift.Array<Mirror.STSOuter>> #0
- super: Mirror.STSContainer<Mirror.STSOuter>.Superclass\n
""")
testSTSDump(STSContainer.Subclass<Int>.ExtraNested(),
STSContainer℠.Subclass<Int>.ExtraNested(),
"""
- Mirror.STSContainer<Mirror.STSOuter>.Subclass<Swift.Int>.ExtraNested #0
- super: Mirror.STSContainer<Mirror.STSOuter>.Superclass\n
""")
testSTSDump(STSContainer.MoreNesting<Bool>.Subclass<Int>(),
STSContainer℠.MoreNesting<Bool>.Subclass<Int>(),
"""
- Mirror.STSContainer<Mirror.STSOuter>.MoreNesting<Swift.Bool>.Subclass<Swift.Int> #0
- super: Mirror.STSContainer<Mirror.STSOuter>.Superclass\n
""")
}
sameTypeSuite.test("Fields") {
testSTSDump(STSContainer.Fields<Int>(),
STSContainer℠.Fields<Int>(),
"""
▿ Mirror.STSContainer<Mirror.STSOuter>.Fields<Swift.Int>
- x: nil
- y: nil\n
""")
}
sameTypeSuite.test("Cases") {
testSTSDump(STSContainer.Cases<Int>.a(.init()),
STSContainer℠.Cases<Int>.a(.init()),
"""
▿ Mirror.STSContainer<Mirror.STSOuter>.Cases<Swift.Int>.a
- a: Mirror.STSOuter\n
""")
testSTSDump(STSContainer.Cases<Int>.b(.init()),
STSContainer℠.Cases<Int>.b(.init()),
"""
▿ Mirror.STSContainer<Mirror.STSOuter>.Cases<Swift.Int>.b
- b: 0\n
""")
}
}
runAllTests()
| apache-2.0 |
ahoppen/swift | stdlib/public/Cxx/std.swift | 1 | 558 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 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
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import std // Clang module
| apache-2.0 |
ahoppen/swift | test/decl/var/property_wrappers.swift | 6 | 59110 | // RUN: %target-typecheck-verify-swift -swift-version 5
// ---------------------------------------------------------------------------
// Property wrapper type definitions
// ---------------------------------------------------------------------------
@propertyWrapper
struct Wrapper<T> {
private var _stored: T
init(stored: T) {
self._stored = stored
}
var wrappedValue: T {
get { _stored }
set { _stored = newValue }
}
}
@propertyWrapper
struct WrapperWithInitialValue<T> {
var wrappedValue: T
init(wrappedValue initialValue: T) {
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperWithDefaultInit<T> {
private var stored: T?
var wrappedValue: T {
get { stored! }
set { stored = newValue }
}
init() {
self.stored = nil
}
}
@propertyWrapper
struct WrapperAcceptingAutoclosure<T> {
private let fn: () -> T
var wrappedValue: T {
return fn()
}
init(wrappedValue fn: @autoclosure @escaping () -> T) {
self.fn = fn
}
init(body fn: @escaping () -> T) {
self.fn = fn
}
}
@propertyWrapper
struct MissingValue<T> { }
// expected-error@-1{{property wrapper type 'MissingValue' does not contain a non-static property named 'wrappedValue'}} {{educational-notes=property-wrapper-requirements}}{{25-25=var wrappedValue: <#Value#>}}
@propertyWrapper
struct StaticValue {
static var wrappedValue: Int = 17
}
// expected-error@-3{{property wrapper type 'StaticValue' does not contain a non-static property named 'wrappedValue'}}{{21-21=var wrappedValue: <#Value#>}}
// expected-error@+1{{'@propertyWrapper' attribute cannot be applied to this declaration}}
@propertyWrapper
protocol CannotBeAWrapper {
associatedtype Value
var wrappedValue: Value { get set }
}
@propertyWrapper
struct NonVisibleValueWrapper<Value> {
private var wrappedValue: Value // expected-error{{private property 'wrappedValue' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleValueWrapper' (which is internal)}} {{educational-notes=property-wrapper-requirements}}
}
@propertyWrapper
struct NonVisibleInitWrapper<Value> {
var wrappedValue: Value
private init(wrappedValue initialValue: Value) { // expected-error{{private initializer 'init(wrappedValue:)' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleInitWrapper' (which is internal)}}
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct InitialValueTypeMismatch<Value> {
var wrappedValue: Value // expected-note{{'wrappedValue' declared here}}
init(wrappedValue initialValue: Value?) { // expected-error{{'init(wrappedValue:)' parameter type ('Value?') must be the same as its 'wrappedValue' property type ('Value') or an @autoclosure thereof}} {{educational-notes=property-wrapper-requirements}}
self.wrappedValue = initialValue!
}
}
@propertyWrapper
struct MultipleInitialValues<Value> {
var wrappedValue: Value? = nil // expected-note 2{{'wrappedValue' declared here}}
init(wrappedValue initialValue: Int) { // expected-error{{'init(wrappedValue:)' parameter type ('Int') must be the same as its 'wrappedValue' property type ('Value?') or an @autoclosure thereof}}
}
init(wrappedValue initialValue: Double) { // expected-error{{'init(wrappedValue:)' parameter type ('Double') must be the same as its 'wrappedValue' property type ('Value?') or an @autoclosure thereof}}
}
}
@propertyWrapper
struct InitialValueFailable<Value> {
var wrappedValue: Value
init?(wrappedValue initialValue: Value) { // expected-error{{property wrapper initializer 'init(wrappedValue:)' cannot be failable}} {{educational-notes=property-wrapper-requirements}}
return nil
}
}
@propertyWrapper
struct InitialValueFailableIUO<Value> {
var wrappedValue: Value
init!(wrappedValue initialValue: Value) { // expected-error{{property wrapper initializer 'init(wrappedValue:)' cannot be failable}}
return nil
}
}
// ---------------------------------------------------------------------------
// Property wrapper type definitions
// ---------------------------------------------------------------------------
@propertyWrapper
struct _lowercaseWrapper<T> {
var wrappedValue: T
}
@propertyWrapper
struct _UppercaseWrapper<T> {
var wrappedValue: T
}
// ---------------------------------------------------------------------------
// Local property wrappers
// ---------------------------------------------------------------------------
func testLocalContext() {
@WrapperWithInitialValue
var x = 17
x = 42
let _: Int = x
let _: WrapperWithInitialValue = _x
@WrapperWithInitialValue(wrappedValue: 17)
var initialValue
let _: Int = initialValue
let _: WrapperWithInitialValue = _initialValue
@Clamping(min: 0, max: 100)
var percent = 50
let _: Int = percent
let _: Clamping = _percent
@WrapperA @WrapperB
var composed = "hello"
let _: WrapperA<WrapperB> = _composed
@WrapperWithStorageRef
var hasProjection = 10
let _: Wrapper = $hasProjection
@WrapperWithInitialValue
var uninitialized: Int { // expected-error {{non-member observing properties require an initializer}}
didSet {}
}
}
// ---------------------------------------------------------------------------
// Limitations on where property wrappers can be used
// ---------------------------------------------------------------------------
enum SomeEnum {
case foo
@Wrapper(stored: 17)
var bar: Int // expected-error{{property 'bar' declared inside an enum cannot have a wrapper}}
// expected-error@-1{{enums must not contain stored properties}}
@Wrapper(stored: 17)
static var x: Int
}
protocol SomeProtocol {
@Wrapper(stored: 17)
var bar: Int // expected-error{{property 'bar' declared inside a protocol cannot have a wrapper}}
// expected-error@-1{{property in protocol must have explicit { get } or { get set } specifier}}
@Wrapper(stored: 17)
static var x: Int // expected-error{{property 'x' declared inside a protocol cannot have a wrapper}}
// expected-error@-1{{property in protocol must have explicit { get } or { get set } specifier}}
}
struct HasWrapper { }
extension HasWrapper {
@Wrapper(stored: 17)
var inExt: Int // expected-error{{property 'inExt' declared inside an extension cannot have a wrapper}}
// expected-error@-1{{extensions must not contain stored properties}}
@Wrapper(stored: 17)
static var x: Int
}
class ClassWithWrappers {
@Wrapper(stored: 17)
var x: Int
}
class Superclass {
var x: Int = 0
}
class SubclassOfClassWithWrappers: ClassWithWrappers {
override var x: Int {
get { return super.x }
set { super.x = newValue }
}
}
class SubclassWithWrapper: Superclass {
@Wrapper(stored: 17)
override var x: Int { get { return 0 } set { } } // expected-error{{property 'x' with attached wrapper cannot override another property}}
}
class C { }
struct BadCombinations {
@WrapperWithInitialValue
lazy var x: C = C() // expected-error{{property 'x' with a wrapper cannot also be lazy}}
@Wrapper
weak var y: C? // expected-error{{property 'y' with a wrapper cannot also be weak}}
@Wrapper
unowned var z: C // expected-error{{property 'z' with a wrapper cannot also be unowned}}
}
struct MultipleWrappers {
// FIXME: The diagnostics here aren't great. The problem is that we're
// attempting to splice a 'wrappedValue:' argument into the call to Wrapper's
// init, but it doesn't have a matching init. We're then attempting to access
// the nested 'wrappedValue', but Wrapper's 'wrappedValue' is Int.
@Wrapper(stored: 17) // expected-error{{cannot convert value of type 'Int' to expected argument type 'WrapperWithInitialValue<Int>'}}
@WrapperWithInitialValue // expected-error{{extra argument 'wrappedValue' in call}}
var x: Int = 17
@WrapperWithInitialValue // expected-error 2{{property wrapper can only apply to a single variable}}
var (y, z) = (1, 2)
}
// ---------------------------------------------------------------------------
// Initialization
// ---------------------------------------------------------------------------
struct Initialization {
@Wrapper(stored: 17)
var x: Int
@Wrapper(stored: 17)
var x2: Double
@Wrapper(stored: 17)
var x3 = 42 // expected-error {{extra argument 'wrappedValue' in call}}
@Wrapper(stored: 17)
var x4
@WrapperWithInitialValue
var y = true
@WrapperWithInitialValue<Int>
var y2 = true // expected-error{{cannot convert value of type 'Bool' to specified type 'Int'}}
mutating func checkTypes(s: String) {
x2 = s // expected-error{{cannot assign value of type 'String' to type 'Double'}}
x4 = s // expected-error{{cannot assign value of type 'String' to type 'Int'}}
y = s // expected-error{{cannot assign value of type 'String' to type 'Bool'}}
}
}
@propertyWrapper
struct Clamping<V: Comparable> {
var value: V
let min: V
let max: V
init(wrappedValue initialValue: V, min: V, max: V) {
value = initialValue
self.min = min
self.max = max
assert(value >= min && value <= max)
}
var wrappedValue: V {
get { return value }
set {
if newValue < min {
value = min
} else if newValue > max {
value = max
} else {
value = newValue
}
}
}
}
struct Color {
@Clamping(min: 0, max: 255) var red: Int = 127
@Clamping(min: 0, max: 255) var green: Int = 127
@Clamping(min: 0, max: 255) var blue: Int = 127
@Clamping(min: 0, max: 255) var alpha: Int = 255
}
func testColor() {
_ = Color(green: 17)
}
// ---------------------------------------------------------------------------
// Wrapper type formation
// ---------------------------------------------------------------------------
@propertyWrapper
struct IntWrapper {
var wrappedValue: Int
}
@propertyWrapper
struct WrapperForHashable<T: Hashable> { // expected-note{{where 'T' = 'NotHashable'}}
var wrappedValue: T
}
@propertyWrapper
struct WrapperWithTwoParams<T, U> {
var wrappedValue: (T, U)
}
struct NotHashable { }
struct UseWrappersWithDifferentForm {
@IntWrapper
var x: Int
@WrapperForHashable // expected-error {{generic struct 'WrapperForHashable' requires that 'NotHashable' conform to 'Hashable'}}
var y: NotHashable
@WrapperForHashable
var yOkay: Int
@WrapperWithTwoParams
var zOkay: (Int, Float)
@HasNestedWrapper.NestedWrapper // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify}}
var w: Int
@HasNestedWrapper<Double>.NestedWrapper
var wOkay: Int
@HasNestedWrapper.ConcreteNestedWrapper
var wOkay2: Int
}
@propertyWrapper
struct Function<T, U> { // expected-note{{'U' declared as parameter to type 'Function'}}
var wrappedValue: (T) -> U?
}
struct TestFunction {
@Function var f: (Int) -> Float?
// FIXME: This diagnostic should be more specific
@Function var f2: (Int) -> Float // expected-error {{property type '(Int) -> Float' does not match 'wrappedValue' type '(Int) -> U?'}}
// expected-error@-1 {{generic parameter 'U' could not be inferred}}
// expected-note@-2 {{explicitly specify}}
func test() {
let _: Int = _f // expected-error{{cannot convert value of type 'Function<Int, Float>' to specified type 'Int'}}
}
}
// ---------------------------------------------------------------------------
// Nested wrappers
// ---------------------------------------------------------------------------
struct HasNestedWrapper<T> { // expected-note {{'T' declared as parameter to type 'HasNestedWrapper'}}
@propertyWrapper
struct NestedWrapper<U> {
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct ConcreteNestedWrapper {
var wrappedValue: T
init(wrappedValue initialValue: T) {
self.wrappedValue = initialValue
}
}
@NestedWrapper
var y: [T] = []
}
struct UsesNestedWrapper<V> {
@HasNestedWrapper<V>.NestedWrapper
var y: [V]
}
// ---------------------------------------------------------------------------
// Referencing the backing store
// ---------------------------------------------------------------------------
struct BackingStore<T> {
@Wrapper
var x: T
@WrapperWithInitialValue
private var y = true // expected-note{{'y' declared here}}
func getXStorage() -> Wrapper<T> {
return _x
}
func getYStorage() -> WrapperWithInitialValue<Bool> {
return self._y
}
}
func testBackingStore<T>(bs: BackingStore<T>) {
_ = bs.x
_ = bs.y // expected-error{{'y' is inaccessible due to 'private' protection level}}
}
// ---------------------------------------------------------------------------
// Explicitly-specified accessors
// ---------------------------------------------------------------------------
struct WrapperWithAccessors {
@Wrapper // expected-error{{property wrapper cannot be applied to a computed property}}
var x: Int {
return 17
}
}
struct UseWillSetDidSet {
@Wrapper
var x: Int {
willSet {
print(newValue)
}
}
@Wrapper
var y: Int {
didSet {
print(oldValue)
}
}
@Wrapper
var z: Int {
willSet {
print(newValue)
}
didSet {
print(oldValue)
}
}
}
struct DidSetUsesSelf {
@Wrapper
var x: Int {
didSet {
print(self)
}
}
}
// ---------------------------------------------------------------------------
// Mutating/nonmutating
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithNonMutatingSetter<Value> {
class Box {
var wrappedValue: Value
init(wrappedValue: Value) {
self.wrappedValue = wrappedValue
}
}
var box: Box
init(wrappedValue initialValue: Value) {
self.box = Box(wrappedValue: initialValue)
}
var wrappedValue: Value {
get { return box.wrappedValue }
nonmutating set { box.wrappedValue = newValue }
}
}
@propertyWrapper
struct WrapperWithMutatingGetter<Value> {
var readCount = 0
var writeCount = 0
var stored: Value
init(wrappedValue initialValue: Value) {
self.stored = initialValue
}
var wrappedValue: Value {
mutating get {
readCount += 1
return stored
}
set {
writeCount += 1
stored = newValue
}
}
}
@propertyWrapper
class ClassWrapper<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
self.wrappedValue = initialValue
}
}
struct UseMutatingnessWrappers {
@WrapperWithNonMutatingSetter
var x = true
@WrapperWithMutatingGetter
var y = 17
@WrapperWithNonMutatingSetter // expected-error{{property wrapper can only be applied to a 'var'}}
let z = 3.14159 // expected-note 2{{change 'let' to 'var' to make it mutable}}
@ClassWrapper
var w = "Hello"
}
func testMutatingness() {
var mutable = UseMutatingnessWrappers()
_ = mutable.x
mutable.x = false
_ = mutable.y
mutable.y = 42
_ = mutable.z
mutable.z = 2.71828 // expected-error{{cannot assign to property: 'z' is a 'let' constant}}
_ = mutable.w
mutable.w = "Goodbye"
let nonmutable = UseMutatingnessWrappers() // expected-note 2{{change 'let' to 'var' to make it mutable}}
// Okay due to nonmutating setter
_ = nonmutable.x
nonmutable.x = false
_ = nonmutable.y // expected-error{{cannot use mutating getter on immutable value: 'nonmutable' is a 'let' constant}}
nonmutable.y = 42 // expected-error{{cannot use mutating getter on immutable value: 'nonmutable' is a 'let' constant}}
_ = nonmutable.z
nonmutable.z = 2.71828 // expected-error{{cannot assign to property: 'z' is a 'let' constant}}
// Okay due to implicitly nonmutating setter
_ = nonmutable.w
nonmutable.w = "World"
}
// ---------------------------------------------------------------------------
// Access control
// ---------------------------------------------------------------------------
struct HasPrivateWrapper<T> {
@propertyWrapper
private struct PrivateWrapper<U> { // expected-note{{type declared here}}
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@PrivateWrapper
var y: [T] = []
// expected-error@-1{{property must be declared private because its property wrapper type uses a private type}}
// Okay to reference private entities from a private property
@PrivateWrapper
private var z: [T]
}
public struct HasUsableFromInlineWrapper<T> {
@propertyWrapper
struct InternalWrapper<U> { // expected-note{{type declared here}}
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@InternalWrapper
@usableFromInline
var y: [T] = []
// expected-error@-1{{property wrapper type referenced from a '@usableFromInline' property must be '@usableFromInline' or public}}
}
@propertyWrapper
class Box<Value> {
private(set) var wrappedValue: Value
init(wrappedValue initialValue: Value) {
self.wrappedValue = initialValue
}
}
struct UseBox {
@Box
var x = 17 // expected-note{{'_x' declared here}}
}
func testBox(ub: UseBox) {
_ = ub.x
ub.x = 5 // expected-error{{cannot assign to property: 'x' is a get-only property}}
var mutableUB = ub
mutableUB = ub
}
func backingVarIsPrivate(ub: UseBox) {
_ = ub._x // expected-error{{'_x' is inaccessible due to 'private' protection level}}
}
// ---------------------------------------------------------------------------
// Memberwise initializers
// ---------------------------------------------------------------------------
struct MemberwiseInits<T> {
@Wrapper
var x: Bool
@WrapperWithInitialValue
var y: T
}
func testMemberwiseInits() {
// expected-error@+1{{type '(Wrapper<Bool>, Double) -> MemberwiseInits<Double>'}}
let _: Int = MemberwiseInits<Double>.init
_ = MemberwiseInits(x: Wrapper(stored: true), y: 17)
}
struct DefaultedMemberwiseInits {
@Wrapper(stored: true)
var x: Bool
@WrapperWithInitialValue
var y: Int = 17
@WrapperWithInitialValue(wrappedValue: 17)
var z: Int
@WrapperWithDefaultInit
var w: Int
@WrapperWithDefaultInit
var optViaDefaultInit: Int?
@WrapperWithInitialValue
var optViaInitialValue: Int?
}
struct CannotDefaultMemberwiseOptionalInit { // expected-note{{'init(x:)' declared here}}
@Wrapper
var x: Int?
}
func testDefaultedMemberwiseInits() {
_ = DefaultedMemberwiseInits()
_ = DefaultedMemberwiseInits(
x: Wrapper(stored: false),
y: 42,
z: WrapperWithInitialValue(wrappedValue: 42))
_ = DefaultedMemberwiseInits(y: 42)
_ = DefaultedMemberwiseInits(x: Wrapper(stored: false))
_ = DefaultedMemberwiseInits(z: WrapperWithInitialValue(wrappedValue: 42))
_ = DefaultedMemberwiseInits(w: WrapperWithDefaultInit())
_ = DefaultedMemberwiseInits(optViaDefaultInit: WrapperWithDefaultInit())
_ = DefaultedMemberwiseInits(optViaInitialValue: nil)
_ = DefaultedMemberwiseInits(optViaInitialValue: 42)
_ = CannotDefaultMemberwiseOptionalInit() // expected-error{{missing argument for parameter 'x' in call}}
_ = CannotDefaultMemberwiseOptionalInit(x: Wrapper(stored: nil))
}
// ---------------------------------------------------------------------------
// Default initializers
// ---------------------------------------------------------------------------
struct DefaultInitializerStruct {
@Wrapper(stored: true)
var x
@WrapperWithInitialValue
var y: Int = 10
}
struct NoDefaultInitializerStruct { // expected-note{{'init(x:)' declared here}}
@Wrapper
var x: Bool
}
class DefaultInitializerClass {
@Wrapper(stored: true)
var x
@WrapperWithInitialValue
final var y: Int = 10
}
class NoDefaultInitializerClass { // expected-error{{class 'NoDefaultInitializerClass' has no initializers}}
@Wrapper
final var x: Bool // expected-note{{stored property 'x' without initial value prevents synthesized initializers}}
}
func testDefaultInitializers() {
_ = DefaultInitializerStruct()
_ = DefaultInitializerClass()
_ = NoDefaultInitializerStruct() // expected-error{{missing argument for parameter 'x' in call}}
}
struct DefaultedPrivateMemberwiseLets {
@Wrapper(stored: true)
private var x: Bool
@WrapperWithInitialValue
var y: Int = 17
@WrapperWithInitialValue(wrappedValue: 17)
private var z: Int
}
func testDefaultedPrivateMemberwiseLets() {
_ = DefaultedPrivateMemberwiseLets()
_ = DefaultedPrivateMemberwiseLets(y: 42)
_ = DefaultedPrivateMemberwiseLets(x: Wrapper(stored: false)) // expected-error{{argument passed to call that takes no arguments}}
}
// ---------------------------------------------------------------------------
// Storage references
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithStorageRef<T> {
var wrappedValue: T
var projectedValue: Wrapper<T> {
return Wrapper(stored: wrappedValue)
}
}
extension Wrapper {
var wrapperOnlyAPI: Int { return 17 }
}
struct TestStorageRef {
@WrapperWithStorageRef var x: Int // expected-note{{'_x' declared here}}
init(x: Int) {
self._x = WrapperWithStorageRef(wrappedValue: x)
}
mutating func test() {
let _: Wrapper = $x
let i = $x.wrapperOnlyAPI
let _: Int = i
// x is mutable, $x is not
x = 17
$x = Wrapper(stored: 42) // expected-error{{cannot assign to property: '$x' is immutable}}
}
}
func testStorageRef(tsr: TestStorageRef) {
let _: Wrapper = tsr.$x
_ = tsr._x // expected-error{{'_x' is inaccessible due to 'private' protection level}}
}
struct TestStorageRefPrivate {
@WrapperWithStorageRef private(set) var x: Int
init() {
self._x = WrapperWithStorageRef(wrappedValue: 5)
}
}
func testStorageRefPrivate() {
var tsr = TestStorageRefPrivate()
let a = tsr.$x // okay, getter is internal
tsr.$x = a // expected-error{{cannot assign to property: '$x' is immutable}}
}
// rdar://problem/50873275 - crash when using wrapper with projectedValue in
// generic type.
@propertyWrapper
struct InitialValueWrapperWithStorageRef<T> {
var wrappedValue: T
init(wrappedValue initialValue: T) {
wrappedValue = initialValue
}
var projectedValue: Wrapper<T> {
return Wrapper(stored: wrappedValue)
}
}
struct TestGenericStorageRef<T> {
struct Inner { }
@InitialValueWrapperWithStorageRef var inner: Inner = Inner()
}
// Wiring up the _projectedValueProperty attribute.
struct TestProjectionValuePropertyAttr {
@_projectedValueProperty(wrapperA)
@WrapperWithStorageRef var a: String
var wrapperA: Wrapper<String> {
Wrapper(stored: "blah")
}
@_projectedValueProperty(wrapperB) // expected-error{{could not find projection value property 'wrapperB'}}
@WrapperWithStorageRef var b: String
}
// ---------------------------------------------------------------------------
// Misc. semantic issues
// ---------------------------------------------------------------------------
@propertyWrapper
struct BrokenLazy { }
// expected-error@-1{{property wrapper type 'BrokenLazy' does not contain a non-static property named 'wrappedValue'}}
struct S {
@BrokenLazy
var wrappedValue: Int
}
@propertyWrapper
struct DynamicSelfStruct {
var wrappedValue: Self { self } // okay
var projectedValue: Self { self } // okay
}
@propertyWrapper
class DynamicSelf {
var wrappedValue: Self { self } // expected-error {{property wrapper wrapped value cannot have dynamic Self type}}
var projectedValue: Self? { self } // expected-error {{property wrapper projected value cannot have dynamic Self type}}
}
struct UseDynamicSelfWrapper {
@DynamicSelf() var value
}
// ---------------------------------------------------------------------------
// Invalid redeclaration
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithProjectedValue<T> {
var wrappedValue: T
var projectedValue: T { return wrappedValue }
}
class TestInvalidRedeclaration1 {
@WrapperWithProjectedValue var i = 17
// expected-note@-1 {{'i' previously declared here}}
// expected-note@-2 {{'$i' synthesized for property wrapper projected value}}
// expected-note@-3 {{'_i' synthesized for property wrapper backing storage}}
@WrapperWithProjectedValue var i = 39
// expected-error@-1 {{invalid redeclaration of 'i'}}
// expected-error@-2 {{invalid redeclaration of synthesized property '$i'}}
// expected-error@-3 {{invalid redeclaration of synthesized property '_i'}}
}
// SR-12839
struct TestInvalidRedeclaration2 {
var _foo1 = 123 // expected-error {{invalid redeclaration of synthesized property '_foo1'}}
@WrapperWithInitialValue var foo1 = 123 // expected-note {{'_foo1' synthesized for property wrapper backing storage}}
}
struct TestInvalidRedeclaration3 {
@WrapperWithInitialValue var foo1 = 123 // expected-note {{'_foo1' synthesized for property wrapper backing storage}}
var _foo1 = 123 // expected-error {{invalid redeclaration of synthesized property '_foo1'}}
}
// Diagnose when wrapped property uses the name we use for lazy variable storage property.
struct TestInvalidRedeclaration4 {
@WrapperWithProjectedValue var __lazy_storage_$_foo: Int
// expected-error@-1 {{invalid redeclaration of synthesized property '$__lazy_storage_$_foo'}}
// expected-note@-2 {{'$__lazy_storage_$_foo' synthesized for property wrapper projected value}}
lazy var foo = 1
}
// ---------------------------------------------------------------------------
// Closures in initializers
// ---------------------------------------------------------------------------
struct UsesExplicitClosures {
@WrapperAcceptingAutoclosure(body: { 42 })
var x: Int
@WrapperAcceptingAutoclosure(body: { return 42 })
var y: Int
}
// ---------------------------------------------------------------------------
// Enclosing instance diagnostics
// ---------------------------------------------------------------------------
@propertyWrapper
struct Observable<Value> {
private var stored: Value
init(wrappedValue: Value) {
self.stored = wrappedValue
}
@available(*, unavailable, message: "must be in a class")
var wrappedValue: Value { // expected-note{{'wrappedValue' has been explicitly marked unavailable here}}
get { fatalError("called wrappedValue getter") }
set { fatalError("called wrappedValue setter") }
}
static subscript<EnclosingSelf>(
_enclosingInstance observed: EnclosingSelf,
wrapped wrappedKeyPath: ReferenceWritableKeyPath<EnclosingSelf, Value>,
storage storageKeyPath: ReferenceWritableKeyPath<EnclosingSelf, Self>
) -> Value {
get {
observed[keyPath: storageKeyPath].stored
}
set {
observed[keyPath: storageKeyPath].stored = newValue
}
}
}
struct MyObservedValueType {
@Observable // expected-error{{'wrappedValue' is unavailable: must be in a class}}
var observedProperty = 17
}
// ---------------------------------------------------------------------------
// Miscellaneous bugs
// ---------------------------------------------------------------------------
// rdar://problem/50822051 - compiler assertion / hang
@propertyWrapper
struct PD<Value> {
var wrappedValue: Value
init<A>(wrappedValue initialValue: Value, a: A) {
self.wrappedValue = initialValue
}
}
struct TestPD {
@PD(a: "foo") var foo: Int = 42
}
protocol P { }
@propertyWrapper
struct WrapperRequiresP<T: P> {
var wrappedValue: T
var projectedValue: T { return wrappedValue }
}
struct UsesWrapperRequiringP {
// expected-note@-1{{in declaration of}}
@WrapperRequiresP var x.: UsesWrapperRequiringP
// expected-error@-1{{expected member name following '.'}}
// expected-error@-2{{expected declaration}}
// expected-error@-3{{type annotation missing in pattern}}
}
// SR-10899 / rdar://problem/51588022
@propertyWrapper
struct SR_10899_Wrapper {
var wrappedValue: String { "hi" }
}
struct SR_10899_Usage {
@SR_10899_Wrapper var thing: Bool // expected-error{{property type 'Bool' does not match 'wrappedValue' type 'String'}}
}
// https://bugs.swift.org/browse/SR-14730
@propertyWrapper
struct StringWrappedValue {
var wrappedValue: String
}
struct SR_14730 {
// expected-error@+1 {{property type '() -> String' does not match 'wrappedValue' type 'String'}}
@StringWrappedValue var value: () -> String
}
// SR-11061 / rdar://problem/52593304 assertion with DeclContext mismatches
class SomeValue {
@SomeA(closure: { $0 }) var some: Int = 100
}
@propertyWrapper
struct SomeA<T> {
var wrappedValue: T
let closure: (T) -> (T)
init(wrappedValue initialValue: T, closure: @escaping (T) -> (T)) {
self.wrappedValue = initialValue
self.closure = closure
}
}
// rdar://problem/51989272 - crash when the property wrapper is a generic type
// alias
typealias Alias<T> = WrapperWithInitialValue<T>
struct TestAlias {
@Alias var foo = 17
}
// rdar://problem/52969503 - crash due to invalid source ranges in ill-formed
// code.
@propertyWrapper
struct Wrap52969503<T> {
var wrappedValue: T
init(blah: Int, wrappedValue: T) { }
}
struct Test52969503 {
@Wrap52969503(blah: 5) var foo: Int = 1 // expected-error{{argument 'blah' must precede argument 'wrappedValue'}}
}
//
// ---------------------------------------------------------------------------
// Property wrapper composition
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperA<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperB<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperC<Value> { // expected-note {{'Value' declared as parameter to type 'WrapperC'}}
var wrappedValue: Value?
init(wrappedValue initialValue: Value?) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperD<Value, X, Y> {
var wrappedValue: Value
}
@propertyWrapper
struct WrapperE<Value> {
var wrappedValue: Value
}
struct TestComposition {
@WrapperA @WrapperB @WrapperC var p1: Int?
@WrapperA @WrapperB @WrapperC var p2 = "Hello"
@WrapperD<WrapperE, Int, String> @WrapperE var p3: Int?
@WrapperD<WrapperC, Int, String> @WrapperC var p4: Int?
@WrapperD<WrapperC, Int, String> @WrapperE var p5: Int // expected-error{{generic parameter 'Value' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}}
// expected-error@-2 {{composed wrapper type 'WrapperE<Int>' does not match type of 'WrapperD<WrapperC<Value>, Int, String>.wrappedValue', which is 'WrapperC<Value>'}}
@Wrapper<String> @Wrapper var value: Int // expected-error{{composed wrapper type 'Wrapper<Int>' does not match type of 'Wrapper<String>.wrappedValue', which is 'String'}}
func triggerErrors(d: Double) { // expected-note 6 {{mark method 'mutating' to make 'self' mutable}} {{2-2=mutating }}
p1 = d // expected-error{{cannot assign value of type 'Double' to type 'Int?'}} {{8-8=Int(}} {{9-9=)}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
p2 = d // expected-error{{cannot assign value of type 'Double' to type 'String?'}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
// TODO(diagnostics): Looks like source range for 'd' here is reported as starting at 10, but it should be 8
p3 = d // expected-error{{cannot assign value of type 'Double' to type 'Int?'}} {{10-10=Int(}} {{11-11=)}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
_p1 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperA<WrapperB<WrapperC<Int>>>'}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
_p2 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperA<WrapperB<WrapperC<String>>>'}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
_p3 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperD<WrapperE<Int?>, Int, String>'}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
}
}
// ---------------------------------------------------------------------------
// Property wrapper composition type inference
// ---------------------------------------------------------------------------
protocol DefaultValue {
static var defaultValue: Self { get }
}
extension Int: DefaultValue {
static var defaultValue: Int { 0 }
}
struct TestCompositionTypeInference {
@propertyWrapper
struct A<Value: DefaultValue> {
var wrappedValue: Value
init(wrappedValue: Value = .defaultValue, key: String) {
self.wrappedValue = wrappedValue
}
}
@propertyWrapper
struct B<Value: DefaultValue>: DefaultValue {
var wrappedValue: Value
init(wrappedValue: Value = .defaultValue) {
self.wrappedValue = wrappedValue
}
static var defaultValue: B<Value> { B() }
}
// All of these are okay
@A(key: "b") @B
var a: Int = 0
@A(key: "b") @B
var b: Int
@A(key: "c") @B @B
var c: Int
}
// ---------------------------------------------------------------------------
// Missing Property Wrapper Unwrap Diagnostics
// ---------------------------------------------------------------------------
@propertyWrapper
struct Foo<T> { // expected-note {{arguments to generic parameter 'T' ('W' and 'Int') are expected to be equal}}
var wrappedValue: T {
get {
fatalError("boom")
}
set {
}
}
var prop: Int = 42
func foo() {}
func bar(x: Int) {}
subscript(q: String) -> Int {
get { return 42 }
set { }
}
subscript(x x: Int) -> Int {
get { return 42 }
set { }
}
subscript(q q: String, a: Int) -> Bool {
get { return false }
set { }
}
}
extension Foo : Equatable where T : Equatable {
static func == (lhs: Foo, rhs: Foo) -> Bool {
lhs.wrappedValue == rhs.wrappedValue
}
}
extension Foo : Hashable where T : Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(wrappedValue)
}
}
@propertyWrapper
struct Bar<T, V> {
var wrappedValue: T
func bar() {}
// TODO(diagnostics): We need to figure out what to do about subscripts.
// The problem standing in our way - keypath application choice
// is always added to results even if it's not applicable.
}
@propertyWrapper
struct Baz<T> {
var wrappedValue: T
func onPropertyWrapper() {}
var projectedValue: V {
return V()
}
}
extension Bar where V == String { // expected-note {{where 'V' = 'Bool'}}
func barWhereVIsString() {}
}
struct V {
func onProjectedValue() {}
}
struct W {
func onWrapped() {}
}
struct MissingPropertyWrapperUnwrap {
@Foo var w: W
@Foo var x: Int
@Bar<Int, Bool> var y: Int
@Bar<Int, String> var z: Int
@Baz var usesProjectedValue: W
func a<T>(_: Foo<T>) {}
func a<T>(named: Foo<T>) {}
func b(_: Foo<Int>) {}
func c(_: V) {}
func d(_: W) {}
func e(_: Foo<W>) {}
subscript<T : Hashable>(takesFoo x: Foo<T>) -> Foo<T> { x }
func baz() {
self.x.foo() // expected-error {{referencing instance method 'foo()' requires wrapper 'Foo<Int>'}}{{10-10=_}}
self.x.prop // expected-error {{referencing property 'prop' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x.bar(x: 42) // expected-error {{referencing instance method 'bar(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.y.bar() // expected-error {{referencing instance method 'bar()' requires wrapper 'Bar<Int, Bool>'}}{{10-10=_}}
self.y.barWhereVIsString() // expected-error {{referencing instance method 'barWhereVIsString()' requires wrapper 'Bar<Int, Bool>'}}{{10-10=_}}
// expected-error@-1 {{referencing instance method 'barWhereVIsString()' on 'Bar' requires the types 'Bool' and 'String' be equivalent}}
self.z.barWhereVIsString() // expected-error {{referencing instance method 'barWhereVIsString()' requires wrapper 'Bar<Int, String>'}}{{10-10=_}}
self.usesProjectedValue.onPropertyWrapper() // expected-error {{referencing instance method 'onPropertyWrapper()' requires wrapper 'Baz<W>'}}{{10-10=_}}
self._w.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
self.usesProjectedValue.onProjectedValue() // expected-error {{referencing instance method 'onProjectedValue()' requires wrapper 'V'}}{{10-10=$}}
self.$usesProjectedValue.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
self._usesProjectedValue.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
a(self.w) // expected-error {{cannot convert value 'w' of type 'W' to expected type 'Foo<W>', use wrapper instead}}{{12-12=_}}
b(self.x) // expected-error {{cannot convert value 'x' of type 'Int' to expected type 'Foo<Int>', use wrapper instead}}{{12-12=_}}
b(self.w) // expected-error {{cannot convert value of type 'W' to expected argument type 'Foo<Int>'}}
e(self.w) // expected-error {{cannot convert value 'w' of type 'W' to expected type 'Foo<W>', use wrapper instead}}{{12-12=_}}
b(self._w) // expected-error {{cannot convert value of type 'Foo<W>' to expected argument type 'Foo<Int>'}}
c(self.usesProjectedValue) // expected-error {{cannot convert value 'usesProjectedValue' of type 'W' to expected type 'V', use wrapper instead}}{{12-12=$}}
d(self.$usesProjectedValue) // expected-error {{cannot convert value '$usesProjectedValue' of type 'V' to expected type 'W', use wrapped value instead}}{{12-13=}}
d(self._usesProjectedValue) // expected-error {{cannot convert value '_usesProjectedValue' of type 'Baz<W>' to expected type 'W', use wrapped value instead}}{{12-13=}}
self.x["ultimate question"] // expected-error {{referencing subscript 'subscript(_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x["ultimate question"] = 42 // expected-error {{referencing subscript 'subscript(_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[x: 42] // expected-error {{referencing subscript 'subscript(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[x: 42] = 0 // expected-error {{referencing subscript 'subscript(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[q: "ultimate question", 42] // expected-error {{referencing subscript 'subscript(q:_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[q: "ultimate question", 42] = true // expected-error {{referencing subscript 'subscript(q:_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
// SR-11476
_ = \Self.[takesFoo: self.x] // expected-error {{cannot convert value 'x' of type 'Int' to expected type 'Foo<Int>', use wrapper instead}}{{31-31=_}}
_ = \Foo<W>.[x: self._x] // expected-error {{cannot convert value '_x' of type 'Foo<Int>' to expected type 'Int', use wrapped value instead}} {{26-27=}}
}
}
struct InvalidPropertyDelegateUse {
// TODO(diagnostics): We need to a tailored diagnostic for extraneous arguments in property delegate initialization
@Foo var x: Int = 42 // expected-error@:21 {{argument passed to call that takes no arguments}}
func test() {
self.x.foo() // expected-error {{value of type 'Int' has no member 'foo'}}
}
}
// SR-11060
class SR_11060_Class {
@SR_11060_Wrapper var property: Int = 1234 // expected-error {{missing argument for parameter 'string' in property wrapper initializer; add 'wrappedValue' and 'string' arguments in '@SR_11060_Wrapper(...)'}}
}
@propertyWrapper
struct SR_11060_Wrapper {
var wrappedValue: Int
init(wrappedValue: Int, string: String) { // expected-note {{'init(wrappedValue:string:)' declared here}}
self.wrappedValue = wrappedValue
}
}
// SR-11138
// Check that all possible compositions of nonmutating/mutating accessors
// on wrappers produce wrapped properties with the correct settability and
// mutatiness in all compositions.
@propertyWrapper
struct NonmutatingGetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
}
}
@propertyWrapper
struct MutatingGetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
}
}
@propertyWrapper
struct NonmutatingGetNonmutatingSetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
nonmutating set { fatalError() }
}
}
@propertyWrapper
struct MutatingGetNonmutatingSetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
nonmutating set { fatalError() }
}
}
@propertyWrapper
struct NonmutatingGetMutatingSetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
mutating set { fatalError() }
}
}
@propertyWrapper
struct MutatingGetMutatingSetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
mutating set { fatalError() }
}
}
struct AllCompositionsStruct {
// Should have nonmutating getter, undefined setter
@NonmutatingGetWrapper @NonmutatingGetWrapper
var ngxs_ngxs: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetWrapper // expected-error{{cannot be composed}}
var ngxs_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngxs_ngns: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetNonmutatingSetWrapper // expected-error{{cannot be composed}}
var ngxs_mgns: Int
// Should have nonmutating getter, undefined setter
@NonmutatingGetWrapper @NonmutatingGetMutatingSetWrapper
var ngxs_ngms: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetMutatingSetWrapper // expected-error{{cannot be composed}}
var ngxs_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetWrapper @NonmutatingGetWrapper
var mgxs_ngxs: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetWrapper // expected-error{{cannot be composed}}
var mgxs_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgxs_ngns: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetNonmutatingSetWrapper // expected-error{{cannot be composed}}
var mgxs_mgns: Int
// Should have mutating getter, undefined setter
@MutatingGetWrapper @NonmutatingGetMutatingSetWrapper
var mgxs_ngms: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetMutatingSetWrapper // expected-error{{cannot be composed}}
var mgxs_mgms: Int
////
// Should have nonmutating getter, undefined setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetWrapper
var ngns_ngxs: Int
// Should have nonmutating getter, undefined setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetWrapper
var ngns_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngns_ngns: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var ngns_mgns: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var ngns_ngms: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetMutatingSetWrapper
var ngns_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetWrapper
var mgns_ngxs: Int
// Should have mutating getter, undefined setter
@MutatingGetNonmutatingSetWrapper @MutatingGetWrapper
var mgns_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgns_ngns: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var mgns_mgns: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var mgns_ngms: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @MutatingGetMutatingSetWrapper
var mgns_mgms: Int
////
// Should have nonmutating getter, undefined setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetWrapper
var ngms_ngxs: Int
// Should have mutating getter, undefined setter
@NonmutatingGetMutatingSetWrapper @MutatingGetWrapper
var ngms_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngms_ngns: Int
// Should have mutating getter, nonmutating setter
@NonmutatingGetMutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var ngms_mgns: Int
// Should have nonmutating getter, mutating setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var ngms_ngms: Int
// Should have mutating getter, mutating setter
@NonmutatingGetMutatingSetWrapper @MutatingGetMutatingSetWrapper
var ngms_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetMutatingSetWrapper @NonmutatingGetWrapper
var mgms_ngxs: Int
// Should have mutating getter, undefined setter
@MutatingGetMutatingSetWrapper @MutatingGetWrapper
var mgms_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgms_ngns: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var mgms_mgns: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var mgms_ngms: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @MutatingGetMutatingSetWrapper
var mgms_mgms: Int
func readonlyContext(x: Int) { // expected-note *{{}}
_ = ngxs_ngxs
// _ = ngxs_mgxs
_ = ngxs_ngns
// _ = ngxs_mgns
_ = ngxs_ngms
// _ = ngxs_mgms
_ = mgxs_ngxs // expected-error{{}}
// _ = mgxs_mgxs
_ = mgxs_ngns // expected-error{{}}
// _ = mgxs_mgns
_ = mgxs_ngms // expected-error{{}}
// _ = mgxs_mgms
_ = ngns_ngxs
_ = ngns_mgxs
_ = ngns_ngns
_ = ngns_mgns
_ = ngns_ngms
_ = ngns_mgms
_ = mgns_ngxs // expected-error{{}}
_ = mgns_mgxs // expected-error{{}}
_ = mgns_ngns // expected-error{{}}
_ = mgns_mgns // expected-error{{}}
_ = mgns_ngms // expected-error{{}}
_ = mgns_mgms // expected-error{{}}
_ = ngms_ngxs
_ = ngms_mgxs // expected-error{{}}
_ = ngms_ngns
_ = ngms_mgns // expected-error{{}}
_ = ngms_ngms
_ = ngms_mgms // expected-error{{}}
_ = mgms_ngxs // expected-error{{}}
_ = mgms_mgxs // expected-error{{}}
_ = mgms_ngns // expected-error{{}}
_ = mgms_mgns // expected-error{{}}
_ = mgms_ngms // expected-error{{}}
_ = mgms_mgms // expected-error{{}}
////
ngxs_ngxs = x // expected-error{{}}
// ngxs_mgxs = x
ngxs_ngns = x
// ngxs_mgns = x
ngxs_ngms = x // expected-error{{}}
// ngxs_mgms = x
mgxs_ngxs = x // expected-error{{}}
// mgxs_mgxs = x
mgxs_ngns = x // expected-error{{}}
// mgxs_mgns = x
mgxs_ngms = x // expected-error{{}}
// mgxs_mgms = x
ngns_ngxs = x // expected-error{{}}
ngns_mgxs = x // expected-error{{}}
ngns_ngns = x
ngns_mgns = x
ngns_ngms = x
ngns_mgms = x
mgns_ngxs = x // expected-error{{}}
mgns_mgxs = x // expected-error{{}}
mgns_ngns = x // expected-error{{}}
mgns_mgns = x // expected-error{{}}
mgns_ngms = x // expected-error{{}}
mgns_mgms = x // expected-error{{}}
ngms_ngxs = x // expected-error{{}}
ngms_mgxs = x // expected-error{{}}
ngms_ngns = x
// FIXME: This ought to be allowed because it's a pure set, so the mutating
// get should not come into play.
ngms_mgns = x // expected-error{{cannot use mutating getter}}
ngms_ngms = x // expected-error{{}}
ngms_mgms = x // expected-error{{}}
mgms_ngxs = x // expected-error{{}}
mgms_mgxs = x // expected-error{{}}
mgms_ngns = x // expected-error{{}}
mgms_mgns = x // expected-error{{}}
mgms_ngms = x // expected-error{{}}
mgms_mgms = x // expected-error{{}}
}
mutating func mutatingContext(x: Int) {
_ = ngxs_ngxs
// _ = ngxs_mgxs
_ = ngxs_ngns
// _ = ngxs_mgns
_ = ngxs_ngms
// _ = ngxs_mgms
_ = mgxs_ngxs
// _ = mgxs_mgxs
_ = mgxs_ngns
// _ = mgxs_mgns
_ = mgxs_ngms
// _ = mgxs_mgms
_ = ngns_ngxs
_ = ngns_mgxs
_ = ngns_ngns
_ = ngns_mgns
_ = ngns_ngms
_ = ngns_mgms
_ = mgns_ngxs
_ = mgns_mgxs
_ = mgns_ngns
_ = mgns_mgns
_ = mgns_ngms
_ = mgns_mgms
_ = ngms_ngxs
_ = ngms_mgxs
_ = ngms_ngns
_ = ngms_mgns
_ = ngms_ngms
_ = ngms_mgms
_ = mgms_ngxs
_ = mgms_mgxs
_ = mgms_ngns
_ = mgms_mgns
_ = mgms_ngms
_ = mgms_mgms
////
ngxs_ngxs = x // expected-error{{}}
// ngxs_mgxs = x
ngxs_ngns = x
// ngxs_mgns = x
ngxs_ngms = x // expected-error{{}}
// ngxs_mgms = x
mgxs_ngxs = x // expected-error{{}}
// mgxs_mgxs = x
mgxs_ngns = x
// mgxs_mgns = x
mgxs_ngms = x // expected-error{{}}
// mgxs_mgms = x
ngns_ngxs = x // expected-error{{}}
ngns_mgxs = x // expected-error{{}}
ngns_ngns = x
ngns_mgns = x
ngns_ngms = x
ngns_mgms = x
mgns_ngxs = x // expected-error{{}}
mgns_mgxs = x // expected-error{{}}
mgns_ngns = x
mgns_mgns = x
mgns_ngms = x
mgns_mgms = x
ngms_ngxs = x // expected-error{{}}
ngms_mgxs = x // expected-error{{}}
ngms_ngns = x
ngms_mgns = x
ngms_ngms = x
ngms_mgms = x
mgms_ngxs = x // expected-error{{}}
mgms_mgxs = x // expected-error{{}}
mgms_ngns = x
mgms_mgns = x
mgms_ngms = x
mgms_mgms = x
}
}
// rdar://problem/54184846 - crash while trying to retrieve wrapper info on l-value base type
func test_missing_method_with_lvalue_base() {
@propertyWrapper
struct Ref<T> {
var wrappedValue: T
}
struct S<T> where T: RandomAccessCollection, T.Element: Equatable {
@Ref var v: T.Element
init(items: T, v: Ref<T.Element>) {
self.v.binding = v // expected-error {{value of type 'T.Element' has no member 'binding'}}
}
}
}
// SR-11288
// Look into the protocols that the type conforms to
// typealias as propertyWrapper //
@propertyWrapper
struct SR_11288_S0 {
var wrappedValue: Int
}
protocol SR_11288_P1 {
typealias SR_11288_Wrapper1 = SR_11288_S0
}
struct SR_11288_S1: SR_11288_P1 {
@SR_11288_Wrapper1 var answer = 42 // Okay
}
// associatedtype as propertyWrapper //
protocol SR_11288_P2 {
associatedtype SR_11288_Wrapper2 = SR_11288_S0
}
struct SR_11288_S2: SR_11288_P2 {
@SR_11288_Wrapper2 var answer = 42 // expected-error {{unknown attribute 'SR_11288_Wrapper2'}}
}
protocol SR_11288_P3 {
associatedtype SR_11288_Wrapper3
}
struct SR_11288_S3: SR_11288_P3 {
typealias SR_11288_Wrapper3 = SR_11288_S0
@SR_11288_Wrapper3 var answer = 42 // Okay
}
// typealias as propertyWrapper in a constrained protocol extension //
protocol SR_11288_P4 {}
extension SR_11288_P4 where Self: AnyObject { // expected-note {{requirement specified as 'Self' : 'AnyObject' [with Self = SR_11288_S4]}}
typealias SR_11288_Wrapper4 = SR_11288_S0
}
struct SR_11288_S4: SR_11288_P4 {
@SR_11288_Wrapper4 var answer = 42 // expected-error {{'Self.SR_11288_Wrapper4' (aka 'SR_11288_S0') requires that 'SR_11288_S4' be a class type}}
}
class SR_11288_C0: SR_11288_P4 {
@SR_11288_Wrapper4 var answer = 42 // Okay
}
// typealias as propertyWrapper in a generic type //
protocol SR_11288_P5 {
typealias SR_11288_Wrapper5 = SR_11288_S0
}
struct SR_11288_S5<T>: SR_11288_P5 {
@SR_11288_Wrapper5 var answer = 42 // Okay
}
// SR-11393
protocol Copyable: AnyObject {
func copy() -> Self
}
@propertyWrapper
struct CopyOnWrite<Value: Copyable> {
init(wrappedValue: Value) {
self.wrappedValue = wrappedValue
}
var wrappedValue: Value
var projectedValue: Value {
mutating get {
if !isKnownUniquelyReferenced(&wrappedValue) {
wrappedValue = wrappedValue.copy()
}
return wrappedValue
}
set {
wrappedValue = newValue
}
}
}
final class CopyOnWriteTest: Copyable {
let a: Int
init(a: Int) {
self.a = a
}
func copy() -> Self {
Self.init(a: a)
}
}
struct CopyOnWriteDemo1 {
@CopyOnWrite var a = CopyOnWriteTest(a: 3)
func foo() { // expected-note{{mark method 'mutating' to make 'self' mutable}}
_ = $a // expected-error{{cannot use mutating getter on immutable value: 'self' is immutable}}
}
}
@propertyWrapper
struct NonMutatingProjectedValueSetWrapper<Value> {
var wrappedValue: Value
var projectedValue: Value {
get { wrappedValue }
nonmutating set { }
}
}
struct UseNonMutatingProjectedValueSet {
@NonMutatingProjectedValueSetWrapper var x = 17
func test() { // expected-note{{mark method 'mutating' to make 'self' mutable}}
$x = 42 // okay
x = 42 // expected-error{{cannot assign to property: 'self' is immutable}}
}
}
// SR-11478
@propertyWrapper
struct SR_11478_W<Value> {
var wrappedValue: Value
}
class SR_11478_C1 {
@SR_11478_W static var bool1: Bool = true // Ok
@SR_11478_W class var bool2: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
@SR_11478_W class final var bool3: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
}
final class SR_11478_C2 {
@SR_11478_W static var bool1: Bool = true // Ok
@SR_11478_W class var bool2: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
@SR_11478_W class final var bool3: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
}
// SR-11381
@propertyWrapper
struct SR_11381_W<T> {
init(wrappedValue: T) {}
var wrappedValue: T {
fatalError()
}
}
struct SR_11381_S {
@SR_11381_W var foo: Int = nil // expected-error {{'nil' is not compatible with expected argument type 'Int'}}
}
// rdar://problem/53349209 - regression in property wrapper inference
struct Concrete1: P {}
@propertyWrapper struct ConcreteWrapper {
var wrappedValue: Concrete1 { get { fatalError() } }
}
struct TestConcrete1 {
@ConcreteWrapper() var s1
func f() {
// Good:
let _: P = self.s1
// Bad:
self.g(s1: self.s1)
// Ugly:
self.g(s1: self.s1 as P)
}
func g(s1: P) {
// ...
}
}
// SR-11477
// Two initializers that can default initialize the wrapper //
@propertyWrapper
struct SR_11477_W1 { // Okay
let name: String
init() {
self.name = "Init"
}
init(name: String = "DefaultParamInit") {
self.name = name
}
var wrappedValue: Int {
get { return 0 }
}
}
// Two initializers with default arguments that can default initialize the wrapper //
@propertyWrapper
struct SR_11477_W2 { // Okay
let name: String
init(anotherName: String = "DefaultParamInit1") {
self.name = anotherName
}
init(name: String = "DefaultParamInit2") {
self.name = name
}
var wrappedValue: Int {
get { return 0 }
}
}
// Single initializer that can default initialize the wrapper //
@propertyWrapper
struct SR_11477_W3 { // Okay
let name: String
init() {
self.name = "Init"
}
var wrappedValue: Int {
get { return 0 }
}
}
// rdar://problem/56213175 - backward compatibility issue with Swift 5.1,
// which unconditionally skipped protocol members.
protocol ProtocolWithWrapper {
associatedtype Wrapper = Float // expected-note{{associated type 'Wrapper' declared here}}
}
struct UsesProtocolWithWrapper: ProtocolWithWrapper {
@Wrapper var foo: Int // expected-warning{{ignoring associated type 'Wrapper' in favor of module-scoped property wrapper 'Wrapper'; please qualify the reference with 'property_wrappers'}}{{4-4=property_wrappers.}}
}
// rdar://problem/56350060 - [Dynamic key path member lookup] Assertion when subscripting with a key path
func test_rdar56350060() {
@propertyWrapper
@dynamicMemberLookup
struct DynamicWrapper<Value> {
var wrappedValue: Value { fatalError() }
subscript<T>(keyPath keyPath: KeyPath<Value, T>) -> DynamicWrapper<T> {
fatalError()
}
subscript<T>(dynamicMember keyPath: KeyPath<Value, T>) -> DynamicWrapper<T> {
return self[keyPath: keyPath] // Ok
}
}
}
// rdar://problem/57411331 - crash due to incorrectly synthesized "nil" default
// argument.
@propertyWrapper
struct Blah<Value> {
init(blah _: Int) { }
var wrappedValue: Value {
let val: Value? = nil
return val!
}
}
struct UseRdar57411331 {
let x = Rdar57411331(other: 5)
}
struct Rdar57411331 {
@Blah(blah: 17) var something: Int?
var other: Int
}
// SR-11994
@propertyWrapper
open class OpenPropertyWrapperWithPublicInit {
public init(wrappedValue: String) { // Okay
self.wrappedValue = wrappedValue
}
open var wrappedValue: String = "Hello, world"
}
// SR-11654
struct SR_11654_S {}
class SR_11654_C {
@Foo var property: SR_11654_S?
}
func sr_11654_generic_func<T>(_ argument: T?) -> T? {
return argument
}
let sr_11654_c = SR_11654_C()
_ = sr_11654_generic_func(sr_11654_c.property) // Okay
// rdar://problem/59471019 - property wrapper initializer requires empty parens
// for default init
@propertyWrapper
struct DefaultableIntWrapper {
var wrappedValue: Int
init() {
self.wrappedValue = 0
}
}
struct TestDefaultableIntWrapper {
@DefaultableIntWrapper var x
@DefaultableIntWrapper() var y
@DefaultableIntWrapper var z: Int
mutating func test() {
x = y
y = z
}
}
@propertyWrapper
public struct NonVisibleImplicitInit {
// expected-error@-1 {{internal initializer 'init()' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleImplicitInit' (which is public)}}
public var wrappedValue: Bool {
return false
}
}
@propertyWrapper
struct OptionalWrapper<T> {
init() {}
var wrappedValue: T? { nil }
}
struct UseOptionalWrapper {
@OptionalWrapper var p: Int?? // Okay
}
@propertyWrapper
struct WrapperWithFailableInit<Value> {
var wrappedValue: Value
init(_ base: WrapperWithFailableInit<Value>) { fatalError() }
init?(_ base: WrapperWithFailableInit<Value?>) { fatalError() }
}
struct TestInitError {
// FIXME: bad diagnostics when a wrapper does not support init from wrapped value
// expected-error@+2 {{extraneous argument label 'wrappedValue:' in call}}
// expected-error@+1 {{cannot convert value of type 'Int' to specified type 'WrapperWithFailableInit<Int>'}}
@WrapperWithFailableInit var value: Int = 10
}
| apache-2.0 |
richardpiazza/SOSwift | Sources/SOSwift/DateTime.swift | 1 | 2346 | import Foundation
public struct DateTime: RawRepresentable, Equatable, Codable {
public typealias RawValue = Date
/// A default `DateFormatter` for interacting with Schema.org date-time formats.
@available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
public static var iso8601: ISO8601DateFormatter {
let formatter = ISO8601DateFormatter()
formatter.formatOptions = .withInternetDateTime
return formatter
}
/// A fallback `DateFormatter` using the format `yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZZZ`
public static var iso8601Simple: DateFormatter {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZZZ"
return formatter
}
public static func makeDate(from stringValue: String) throws -> Date {
let _date: Date?
if #available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) {
_date = iso8601.date(from: stringValue)
} else {
_date = iso8601Simple.date(from: stringValue)
}
guard let date = _date else {
throw SchemaError.incorrectDateFormat
}
return date
}
public static func makeString(from date: Date) -> String {
if #available(macOS 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *) {
return iso8601.string(from: date)
} else {
return iso8601Simple.string(from: date)
}
}
public var rawValue: Date
public init(rawValue: Date) {
self.rawValue = rawValue
}
public init?(stringValue: String) {
let date: Date
do {
date = try type(of: self).makeDate(from: stringValue)
} catch {
return nil
}
rawValue = date
}
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let value = try container.decode(String.self)
rawValue = try type(of: self).makeDate(from: value)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(stringValue)
}
public var stringValue: String {
return type(of: self).makeString(from: rawValue)
}
}
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.