“与”在Swift初始化中的参数名称 [英] "with" in parameter names in Swift initialisers

查看:144
本文介绍了“与”在Swift初始化中的参数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此初始化程序将导致错误,抱怨初始化程序的第一个参数隐含了with;你是说名字吗?

  init(withName:String){

}

我不知道这是什么意思,如果它自动提供 withName 外部参数名称如果我调用它的名称或什么...



如果我将其更改为

  init(name:String){

}

任何尝试调用 init(with:joe) init(withName:Joe )将失败。所以我不知道错误消息告诉我,如何声明它,所以我调用它 init(withName:joe)

$ b在Swift中,你不应该向初始化器添加

初始化程序应该是 init(name:),你应该调用 Object(name:joe)



这是因为Swift方法如何桥接到ObjC。在ObjC中,该初始化程序将自动转换为 initWithName:。如果你命名它 init(withName:)它会变成 initWithWithName:


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){

}

I'm not sure what this means, if it provides automagically the withName external parameter name if I call it name or what...

If I change it to

init(name: String){

}

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").

解决方案

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").

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初始化中的参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆