为什么不使用new()类方法在Swift中创建对象? [英] Why using new() class method to create an object in Swift doesn't compile?

查看:53
本文介绍了为什么不使用new()类方法在Swift中创建对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Objective-C中,我不是 new 的忠实拥护者.但是这个问题提出了疑问.为什么不能编译?:

I wasn't a big fan of new in Objective-C. But this question raised the doubt. Why this does not compile?:

let j = NSNumber.new()
var s = NSString.new()

看起来像 new()是常规的类方法.尽管在Apple的文档中,在名称??

Looks like new() is a regular class method. Although in Apple's doc is defined with back ticks around the name ??

class func `new`() -> Self!

因此,问题仍然存在.如果NSObject中有 new(),为什么不编译?文件雷达?

So, the question remains. If new() is there in NSObject, why does not compile? File Radar?

推荐答案

new 是保留关键字,您必须使用反引号将其转义.这将起作用:

new is a reserved keyword and you have to escape it with backticks. This will work:

let string = NSString.`new`()

但是我建议使用"Swift"方式,因为它更短,更干净并且适用于非 NSObject 种:

But I recommend using the "Swift" way as it shorter, cleaner and works for non NSObject kinds:

let string = NSString()

这篇关于为什么不使用new()类方法在Swift中创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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