Swift协议函数:返回相同类型的符合类

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)

可能吗?

Luc*_*tti 7

只需使用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)