1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
|
//===--- generic_subscript.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: %target-run-simple-swift
// REQUIRES: executable_test
//
import StdlibUnittest
var GenericSubscriptTestSuite = TestSuite("GenericSubscript")
struct S<T> : P {
typealias Element = T
var t: T
subscript<U>(a: (T) -> U, b: (U) -> T) -> U {
get {
print(T.self)
print(U.self)
return a(t)
}
set {
print(T.self)
print(U.self)
t = b(newValue)
}
}
}
protocol P {
associatedtype Element
subscript<U>(a: (Element) -> U, b: (U) -> Element) -> U { get set }
}
func increment<T : P>(p: inout T) where T.Element == String {
p[{Int($0)!}, {String($0)}] += 1
}
GenericSubscriptTestSuite.test("Basic") {
var s = S<String>(t: "0")
increment(p: &s)
expectEqual(s.t, "1")
}
protocol AnySubscript {
subscript(k: AnyHashable) -> Any? { get set }
}
struct AnyDictionary : AnySubscript {
var dict: [AnyHashable : Any] = [:]
subscript(k: AnyHashable) -> Any? {
get {
return dict[k]
}
set {
dict[k] = newValue
}
}
}
extension AnySubscript {
subscript<K : Hashable, V>(k k: K) -> V? {
get {
return self[k] as! V?
}
set {
self[k] = newValue
}
}
}
GenericSubscriptTestSuite.test("ProtocolExtensionConcrete") {
var dict = AnyDictionary()
func doIt(dict: inout AnyDictionary) {
dict["a" ] = 0
dict[k: "a"]! += 1
}
doIt(dict: &dict)
expectEqual(dict["a"]! as! Int, 1)
expectEqual(dict[k: "a"]!, 1)
}
GenericSubscriptTestSuite.test("ProtocolExtensionAbstract") {
var dict = AnyDictionary()
func doIt<T : AnySubscript>(dict: inout T) {
dict["a" ] = 0
dict[k: "a"]! += 1
}
doIt(dict: &dict)
expectEqual(dict["a"]! as! Int, 1)
expectEqual(dict[k: "a"]!, 1)
}
protocol GenericSubscript : AnySubscript {
subscript<K : Hashable, V>(k k: K) -> V? { get set }
}
extension AnyDictionary : GenericSubscript { }
GenericSubscriptTestSuite.test("ProtocolExtensionWitness") {
var dict = AnyDictionary()
func doIt<T : GenericSubscript>(dict: inout T) {
dict["a" ] = 0
dict[k: "a"]! += 1
}
doIt(dict: &dict)
expectEqual(dict["a"]! as! Int, 1)
expectEqual(dict[k: "a"]!, 1)
}
runAllTests()
|