相关疑难解决方法(0)

Protocol func返回Self

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

protocol P {
    func copy() -> Self
}
Run Code Online (Sandbox Code Playgroud)

以及实现P的C类:

class C : P {
    func copy() -> Self {
        return C()
    }
}
Run Code Online (Sandbox Code Playgroud)

但是,我是否输入返回值,因为Self我得到以下错误:

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

我也试过回来了C.

class C : P {
    func copy() -> C  {
        return C()
    }
}
Run Code Online (Sandbox Code Playgroud)

这导致以下错误:

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

没有什么可行的,除了我前缀class Cfinalie 的情况:

final class C : P {
    func copy() -> C  {
        return C()
    }
}
Run Code Online (Sandbox Code Playgroud)

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

protocols subclassing swift swift-protocols

70
推荐指数
5
解决办法
2万
查看次数

为什么Self和self有时会在静态函数中引用不同的类型?

最近,我一直在使用Swift开发多个面向协议的应用程序框架,并注意到协议扩展中有一些(看似)奇怪的静态函数行为,特别是从元类型调用扩展函数的情况.

我最初发现这些行为的方式是对一个错误进行故障排除,其中一个对象的类型以一种看似不可能的方式发生了变化.我追查了问题并最终确定这是因为在静态函数中,Self并且self可能存在不同的类型(注意:我已经分别称这些为"Big S Self"和"Little s self").我将用我在游乐场中掀起的一些简单的例子来证明这一点:

class SomeBaseClass: SomeProtocol {}

class SomeChildClass: SomeBaseClass {}

protocol SomeProtocol {}

extension SomeProtocol {
    static private func getName() -> String {
        return "\(self): \(type(of: self))"
    }

    static func ambiguousName() -> String {
        return getName()
    }

    static func littleName() -> String {
        return self.getName()
    }

    static func bigName() -> String {
        return Self.getName()
    }
}

let child: SomeBaseClass.Type = SomeChildClass.self // SomeChildClass.Type

print(child.ambiguousName())          // "SomeChildClass: SomeBaseClass.Type\n"
print(child.littleName())             // "SomeChildClass: SomeBaseClass.Type\n"
print(child.bigName()) …
Run Code Online (Sandbox Code Playgroud)

swift swift-protocols swift3

12
推荐指数
1
解决办法
1226
查看次数

swift 'self' 和 'Self' 有什么区别?

在此处输入图片说明

问题:“自我”和“自我”有什么区别?当我在超类中定义函数以返回子类的类型时,如何在函数实现中使用“Self”?

我应该代表函数调用者的自身类型返回什么类型?基类型是 NSObject 吗?

swift

1
推荐指数
1
解决办法
3425
查看次数

标签 统计

swift ×3

swift-protocols ×2

protocols ×1

subclassing ×1

swift3 ×1