0
次のように動作します。重要なことは、func1
とfunc2
は、私はしかし、どこジェネリッククラスとそのプロトコル、この「戻りオブジェクト制約を持つプロトコルに」行動を再現したいと思いますMySecondClassProtocol
クラスを返す際に汎用プロトコル制約を適用する
import Foundation
protocol MyIntProtocol: class {
var value: Int? { get set }
func fulfill(_ result: Int)
}
final class MyIntClass: MyIntProtocol {
var value: Int?
func fulfill(_ result: Int) { self.value = result }
}
protocol MyFirstClassProtocol: class {
func func1(_ value: MyIntProtocol) -> MySecondClassProtocol
}
protocol MySecondClassProtocol: class {
func func2(_ value: MyIntProtocol) -> MySecondClassProtocol
func func3(_ value: MyIntProtocol)
}
final class MyClass: MyFirstClassProtocol, MySecondClassProtocol {
func func1(_ value: MyIntProtocol) -> MySecondClassProtocol {
print(value.value!)
return self
}
func func2(_ value: MyIntProtocol) -> MySecondClassProtocol {
print(value.value!)
return self
}
func func3(_ value: MyIntProtocol) { print(value.value!) }
}
let e = MyIntClass()
e.fulfill(23)
let m = MyClass()
// m has func1, func2 and func3 methods
let n = m.func1(e)
// n has func2 and func3 methods
let o = n.func2(e)
// o has func2 and func3 methods
o.func3(e)
に拘束されMyClass
オブジェクトへのインターフェイスを返します現在導入されています。
以下はコンパイルされますが、返されるオブジェクトはfunc1
とfunc2
で、MySecondClassProtocol
には制約されません。
import Foundation
protocol MyGenericProtocol: class {
associatedtype ValueType
var value: ValueType? { get set }
func fulfill(_ result: ValueType)
}
final class MyGenericClass<T>: MyGenericProtocol {
var value: T?
func fulfill(_ result: T) { self.value = result }
}
protocol MyFirstClassProtocol: class {
associatedtype T: MyGenericProtocol
associatedtype U: MySecondClassProtocol
func func1(_ value: T) -> U
}
protocol MySecondClassProtocol: class {
associatedtype T: MyGenericProtocol
associatedtype U: Self
func func2(_ value: T) -> U
func func3(_ value: T)
}
final class MyClass: MyFirstClassProtocol, MySecondClassProtocol {
func func1(_ value: MyGenericClass<Int>) -> MyClass {
print(value.value!)
return self
}
func func2(_ value: MyGenericClass<Int>) -> MyClass {
print(value.value!)
return self
}
func func3(_ value: MyGenericClass<Int>) { print(value.value!) }
}
let e = MyGenericClass<Int>()
e.fulfill(23)
let m = MyClass()
// m has func1, func2 and func3 methods
let n = m.func1(e)
// n has func1, func2 and func3 methods
// Wanting only func2 and func3 methods available
let o = n.func2(e)
// o has func1, func2 and func3 methods
// Wanting only func2 and func3 methods available
o.func3(e)
これを達成するにはどうすればいいですか?ありがとう!!