swift - 是否禁止协议(protocol)类型的 inout 变量?

标签 swift swift2 xcode7-beta5

以下代码:

protocol SomeProtocol {}
class SomeClass: SomeProtocol {}

private func doSomethingWith(inout someVar: SomeProtocol) {}

private var someGlobalVar = SomeClass() // inferring SomeClass's type

doSomethingWith(&someGlobalVar)

产生以下错误:

Cannot invoke 'doSomethingWith' with an argument list of type '(inout SomeClass)'

将倒数第二行更改为 private var someGlobalVar: SomeProtocol = SomeClass() 可解决错误。

主题。

最佳答案

除了@Sulthan说的,还有两种可能的解决方案, 取决于您的功能需要做什么。

您可以使函数通用:

func doSomethingWith<T : SomeProtocol>(inout someVar: T) {}

现在您可以传递任何符合协议(protocol)的类的实例:

var someGlobalVar = SomeClass()
doSomethingWith(&someGlobalVar)

如果您只使用 的实例并且只使用函数 修改实例指向的对象的属性,那么您根本不需要 inout 参数,因为类是引用类型。 你只需要将协议(protocol)标记为“类协议(protocol)”:

protocol SomeProtocol : class {
    var name : String { get set }
}
class SomeClass: SomeProtocol {
    var name : String = ""
}

func doSomethingWith(someVar: SomeProtocol) {
    // Modify the object:
    someVar.name = "modfied"
}

var someGlobalVar = SomeClass()
doSomethingWith(someGlobalVar)
print(someGlobalVar.name) // "modified"

关于swift - 是否禁止协议(protocol)类型的 inout 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31960117/

相关文章:

ios - Swift 2 官方指南/文档链接?

Xcode 在打开时总是弹出验证

ios - Swift advancedBy 无法处理换行符 "\r\n"

xcode - Bool 不是 ObjCBool​​ 的子类型 - swift 2 beta 5

ios - 命令/Applications/Xcode-beta.app/Contents/Developer/usr/bin/actool 失败,退出代码为 255

ios - 在应用程序启动时获取在 UITabBarController 中选择的选项卡的标题

javascript - HttpRequest 使用来自数组 Parse.com Cloudcode 的多个 URL

ios - 运行时的 Swift 方法反射

swift - NSManagedObject 如何符合 NSItemProviderReading 协议(protocol)?

swift - 从仅解包选项中向下转换;您是要使用 '!' 吗?