为什么使用new()类方法在Swift中创建对象无法编译?

编程入门 行业动态 更新时间:2024-10-10 02:14:28
本文介绍了为什么使用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`()

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

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

let string = NSString()

更多推荐

为什么使用new()类方法在Swift中创建对象无法编译?

本文发布于:2023-11-26 09:01:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1633473.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   方法   Swift

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!