4bo*_*lie 6 swift swift-protocols
我想知道是否可以在Swift中完成类似java(或c ++)的事情:
我有一个协议:
protocol Prot1 {
func returnMyself() -> Prot1
}
Run Code Online (Sandbox Code Playgroud)
一个类符合协议Prot1.我可以强制函数的返回类型returnMyself()与下面的类的类型相同吗?
class MyClass: Prot1 {
public func returnMyself() -> MyClass {
return self
}
}
Run Code Online (Sandbox Code Playgroud)
可能吗?
Self您的协议protocol Prot1 {
func returnMyself() -> Prot1
}
Run Code Online (Sandbox Code Playgroud)
protocol Animal {
func mySelf() -> Self
}
class Feline: Animal {
func mySelf() -> Self {
return self
}
}
class Cat: Feline { }
Feline().mySelf() // Feline
Cat().mySelf() // Cat
Run Code Online (Sandbox Code Playgroud)
你也可以像这样在协议扩展中使用Self
protocol Animal {}
extension Animal {
func mySelf() -> Self {
return self
}
}
Run Code Online (Sandbox Code Playgroud)
现在一个类只需要像这样符合Animal
class Feline: Animal { }
class Cat: Feline { }
class Dog: Animal {}
Run Code Online (Sandbox Code Playgroud)
并自动获取方法
Feline().mySelf() // Feline
Cat().mySelf() // Cat
Dog().mySelf() // Dog
Run Code Online (Sandbox Code Playgroud)
protocol ReadableInterval { }
class Interval: ReadableInterval { }
protocol ReadableEvent {
associatedtype IntervalType: ReadableInterval
func getInterval() -> IntervalType
}
class Event: ReadableEvent {
typealias IntervalType = Interval
func getInterval() -> Interval {
return Interval()
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
699 次 |
| 最近记录: |