问题描述
这个初始化器会导致一个错误,抱怨 "with" 隐含在初始化器的第一个参数中;你是说名字吗?
This initialiser will cause an error complaining that "with" is implied for the first parameter of an initialiser; did you mean name?
init(withName: String){
}
我不确定这意味着什么,如果它自动提供 withName
外部参数名称,如果我称它为 name 或什么...
I'm not sure what this means, if it provides automagically the withName
external parameter name if I call it name or what...
如果我把它改成
init(name: String){
}
任何调用它 init(with: "joe")
或 init(withName: "Joe")
的尝试都会失败.所以我不知道错误消息告诉我什么以及如何声明它,所以我称之为 init(withName: "joe")
.
any attempt at calling it init(with: "joe")
or init(withName: "Joe")
will fail. So I have no idea what the error message is telling me and how I can declare it so I call it init(withName: "joe")
.
推荐答案
在 Swift 中,你不应该将 with
添加到初始化程序中.初始化程序应该是 init(name:)
并且你应该把它称为 Object(name: "joe")
.
In Swift you should not add with
to the initializer. The initializer should be init(name:)
and you should call it as Object(name: "joe")
.
这是因为 Swift 方法如何桥接到 ObjC.在 ObjC 中,该初始化程序将自动转换为 initWithName:
.如果您将其命名为 init(withName:)
,它将变为 initWithWithName:
.
This is because of how Swift methods bridge to ObjC. In ObjC, that initializer will automatically be translated to initWithName:
. If you named it init(withName:)
it would become initWithWithName:
.
这篇关于“与"在 Swift 初始化程序中的参数名称中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!