Protocol func返回Self

问题描述 投票:64回答:8

我有一个协议P,它返回一个对象的副本:

protocol P {
    func copy() -> Self
}

以及实现P的C类:

class C : P {
    func copy() -> Self {
        return C()
    }
}

但是,我是否将返回值作为Self我得到以下错误:

无法将类型为“C”的返回表达式转换为返回类型“Self”

我也尝试过返回C

class C : P {
    func copy() -> C  {
        return C()
    }
}

这导致以下错误:

非终结类'C'中的方法'copy()'必须返回Self以符合协议'P'

没有什么可行的,除了我用class C加上前缀final的情况,即:

final class C : P {
    func copy() -> C  {
        return C()
    }
}

但是,如果我想继承C,那么什么都行不通。有没有办法解决?

swift protocols subclassing swift-protocols
8个回答
135
投票

问题是你承诺编译器无法证明你会保留。

所以你创造了这个承诺:调用copy()将返回自己的类型,完全初始化。

但是你用这种方式实现了copy()

func copy() -> Self {
    return C()
}

现在我是一个不会覆盖copy()的子类。我返回一个C,而不是一个完全初始化的Self(我承诺)。所以这不好。怎么样:

func copy() -> Self {
    return Self()
}

好吧,那不会编译,但即使它确实如此,也没有好处。子类可能没有普通的构造函数,因此D()甚至可能不合法。 (虽然见下文。)

好吧,那怎么样:

func copy() -> C {
    return C()
}

是的,但这不会返回Self。它返回C。你还没有履行诺言。

“但是ObjC可以做到!”好吧,有点。主要是因为它并不关心你是否像Swift那样遵守诺言。如果未能在子类中实现copyWithZone:,则可能无法完全初始化对象。编译器甚至不会警告你,你已经这样做了。

“但ObjC中的大部分内容都可以翻译成Swift,而ObjC则有NSCopying。”是的确如此,以下是它的定义:

func copy() -> AnyObject!

所以你也可以这样做(这里没有理由!)

protocol Copyable {
  func copy() -> AnyObject
}

这说:“我对你得到的东西没有任何承诺。”你也可以说:

protocol Copyable {
  func copy() -> Copyable
}

这是你可以做出的承诺。

但我们可以暂时考虑一下C ++并记住我们可以做出的承诺。我们可以保证我们和我们所有的子类都将实现特定类型的初始化器,Swift将强制执行(因此可以证明我们说实话):

protocol Copyable {
  init(copy: Self)
}

class C : Copyable {
  required init(copy: C) {
    // Perform your copying here.
  }
}

这就是你应该如何进行复制。

我们可以更进一步,但它使用dynamicType,我没有广泛测试它以确保它总是我们想要的,但它应该是正确的:

protocol Copyable {
  func copy() -> Self
  init(copy: Self)
}

class C : Copyable {
  func copy() -> Self {
    return self.dynamicType(copy: self)
  }

  required init(copy: C) {
    // Perform your copying here.
  }
}

在这里,我们保证有一个初始化程序为我们执行副本,然后我们可以在运行时确定要调用哪个,给我们您正在寻找的方法语法。


24
投票

使用Swift 2,我们可以使用协议扩展。

protocol Copyable {
    init(copy:Self)
}

extension Copyable {
    func copy() -> Self {
        return Self.init(copy: self)
    }
}

13
投票

还有另一种方法可以做你想要的,包括利用Swift的相关类型。这是一个简单的例子:

public protocol Creatable {

    associatedtype ObjectType = Self

    static func create() -> ObjectType
}

class MyClass {

    // Your class stuff here
}

extension MyClass: Creatable {

    // Define the protocol function to return class type
    static func create() -> MyClass {

         // Create an instance of your class however you want
        return MyClass()
    }
}

let obj = MyClass.create()

10
投票

实际上,有一个技巧可以在协议(Self)要求时轻松返回gist

/// Cast the argument to the infered function return type.
func autocast<T>(some: Any) -> T? {
    return some as? T
}

protocol Foo {
    static func foo() -> Self
}

class Vehicle: Foo {
    class func foo() -> Self {
        return autocast(Vehicle())!
    }
}

class Tractor: Vehicle {
    override class func foo() -> Self {
        return autocast(Tractor())!
    }
}

func typeName(some: Any) -> String {
    return (some is Any.Type) ? "\(some)" : "\(some.dynamicType)"
}

let vehicle = Vehicle.foo()
let tractor = Tractor.foo()

print(typeName(vehicle)) // Vehicle
print(typeName(tractor)) // Tractor

2
投票

根据Rob的建议,这可以通过associated types更加通用。我已经改变了一些例子来证明这种方法的好处。

protocol Copyable: NSCopying {
    associatedtype Prototype
    init(copy: Prototype)
    init(deepCopy: Prototype)
}
class C : Copyable {
    typealias Prototype = C // <-- requires adding this line to classes
    required init(copy: Prototype) {
        // Perform your copying here.
    }
    required init(deepCopy: Prototype) {
        // Perform your deep copying here.
    }
    @objc func copyWithZone(zone: NSZone) -> AnyObject {
        return Prototype(copy: self)
    }
}

1
投票

我有一个类似的问题,并提出了一些可能有用的东西,所以我会分享它以供将来参考,因为这是我在寻找解决方案时找到的第一个地方之一。

如上所述,问题是copy()函数的返回类型的模糊性。通过分离copy() - > C和copy() - > P函数可以非常清楚地说明这一点:

因此,假设您按如下方式定义协议和类:

protocol P
{
   func copy() -> P
}

class C:P  
{        
   func doCopy() -> C { return C() }       
   func copy() -> C   { return doCopy() }
   func copy() -> P   { return doCopy() }       
}

当返回值的类型是显式时,这将编译并生成预期结果。每当编译器必须决定返回类型应该是什么时(它自己),它将发现情况不明确并且对于实现P协议的所有具体类都失败。

例如:

var aC:C = C()   // aC is of type C
var aP:P = aC    // aP is of type P (contains an instance of C)

var bC:C         // this to test assignment to a C type variable
var bP:P         //     "       "         "      P     "    "

bC = aC.copy()         // OK copy()->C is used

bP = aC.copy()         // Ambiguous. 
                       // compiler could use either functions
bP = (aC as P).copy()  // but this resolves the ambiguity.

bC = aP.copy()         // Fails, obvious type incompatibility
bP = aP.copy()         // OK copy()->P is used

总之,这可以在你不是使用基类的copy()函数或者总是有显式类型上下文的情况下工作。

我发现使用相同的函数名作为具体的类,无处不在的代码,所以我最终使用了一个不同的名称的协议的copy()函数。

最终结果更像是:

protocol P
{
   func copyAsP() -> P
}

class C:P  
{
   func copy() -> C 
   { 
      // there usually is a lot more code around here... 
      return C() 
   }
   func copyAsP() -> P { return copy() }       
}

当然,我的背景和功能完全不同,但在问题的精神上,我试图尽可能接近给出的例子。


0
投票

把帽子扔到戒指里。我们需要一个协议,返回应用协议类型的可选项。我们还希望覆盖显式返回类型,而不仅仅是Self。

诀窍不是使用'Self'作为返回类型,而是定义一个您设置为等于Self的关联类型,然后使用该关联类型。

这是旧的方式,使用Self ...

protocol Mappable{
    static func map() -> Self?
}

// Generated from Fix-it
extension SomeSpecificClass : Mappable{
    static func map() -> Self? {
        ...
    }
}

这是使用关联类型的新方法。请注意,返回类型现在是显式的,而不是“Self”。

protocol Mappable{
    associatedtype ExplicitSelf = Self
    static func map() -> ExplicitSelf?
}

// Generated from Fix-it
extension SomeSpecificClass : Mappable{
    static func map() -> SomeSpecificClass? {
        ...
    }
}

0
投票

要使用associatedtype方式添加答案,我建议将实例的创建移动到协议扩展的默认实现。通过这种方式,符合要求的类将不必实现它,从而使我们免于代码重复:

protocol Initializable {
    init()
}

protocol Creatable: Initializable {
    associatedtype Object: Initializable = Self
    static func newInstance() -> Object
}

extension Creatable {
    static func newInstance() -> Object {
        return Object()
    }
}

class MyClass: Creatable {
    required init() {}
}

class MyOtherClass: Creatable {
    required init() {}
}

// Any class (struct, etc.) conforming to Creatable
// can create new instances without having to implement newInstance() 
let instance1 = MyClass.newInstance()
let instance2 = MyOtherClass.newInstance()
© www.soinside.com 2019 - 2024. All rights reserved.