gpt4 book ai didi

swift - 无法使用类型为 '' 的参数列表调用 ''

转载 作者:搜寻专家 更新时间:2023-11-01 06:20:46 25 4
gpt4 key购买 nike

在 Playground(Xcode 7.2(7C68)) 中,我正在使用泛型函数并收到错误:

Cannont invoke 'requires' with an argument list of type 'MyClass'

Playground 代码:

import Foundation

public protocol Proto {
func someFunction()
}

func requires<T: Proto>(param: T) -> Bool
{
if param is NSObject
{
return true
}
else
{
return false
}
}


class MyClass:NSObject, Proto {
var name: String
required init?(response: String){
self.name = response
}

func someFunction(){
print(name)
}
}

var m = MyClass(response: "Hey there")
requires(m) // Cannont invoke 'requires' with an argument list of type 'MyClass'

如果我删除 init 函数它会起作用 - 你知道为什么吗?:

需要初始化吗?(响应:字符串){ self.name = 回应

最佳答案

required init?(response: String) { ... }

是一个可失败初始化器,因此

var m = MyClass(response: "Hey there")

可选 类型的 MyClass?。你必须解开值(value),或使用可选绑定(bind):

if let m = MyClass(response: "Hey there") {
requires(m)
}

MyClass 符合 Proto,但 MyClass? 不符合。

但是您的实现不会失败(即返回 nil)完全没有,因此您也可以通过删除问号使初始化程序不可失败:

required init(response: String) { ... }

关于swift - 无法使用类型为 '' 的参数列表调用 '',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34683811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com