ios – 在这个例子中使用隐式解包的可选项有什么意义?

ios – 在这个例子中使用隐式解包的可选项有什么意义?,第1张

概述这是来自文档,第 Failable Initializers for Classes节: class Product { let name: String! init?(name: String) { self.name = name if name.isEmpty { return nil } }}if let @H_301_6@ 这是来自文档,第 Failable Initializers for Classes节:

class Product {     let name: String!     init?(name: String) {           self.name = name           if name.isEmpty { return nil }     }}if let bowTIE = Product(name: "") {   // no need to check if bowTIE.name == nil   print("The product's name is \(bowTIE.name)")}

这描述如下:

In the example above,the name property of the Product class is
defined as having an implicitly unwrapped optional string type
(String!). Because it is of an optional type,this means that the name
property has a default value of nil before it is assigned a specific
value during initialization. This default value of nil in turn means
that all of the propertIEs introduced by the Product class have a
valID initial value. As a result,the failable initializer for Product
can trigger an initialization failure at the start of the initializer
if it is passed an empty string,before assigning a specific value to
the name property within the initializer.

看看最后一句话:

As a result,before assigning a specific value to
the name property within the initializer.

从提供的代码中看不到这一点.在提供的代码中,可以看到在返回nil部分之前发生了赋值,并且String(非可选)或String? (可选)会起作用.

另一件事是,在提供的示例中,如果将其定义为常量,则使用隐式展开的可选项是没有意义的.必须在init完成之前将常量初始化为默认值.

对此有任何想法,或者是否有人看到不提出雷达的理由?也许我错过了什么?我有一个想法实际上为什么隐式解包可选在这里使用,但它是一个坏的例子.对我来说,这会更有意义:

class Product {    var name: String! //let is changed to var    init?(name: String) {       if name.isEmpty { return nil } //Check here if passed value is non-empty       self.name = name    }}

这样,可以在对name属性进行任何赋值之前触发初始化失败.

解决方法 您对误导性文档的所有疑虑都是正确的.

此外,请注意,在Swift 2.2中,从可用的初始化程序返回早期确实有效,甚至在所有属性初始化之前:

class Product {    let name: String    init?(name: String) {        if name.isEmpty { return nil }        self.name = name    }}

另一个变化是,当从可用的初始化程序返回nil时,不再调用deinit.

来自Xcode 7.3 beta 2 Release Notes:

InsIDe a class,a designated initializer that is either failable (init?()) or throwing (init() throws) is allowed to exit before initializing all stored propertIEs and calling super.init(). This behavior is supported,making designated initializers more consistent with convenIEnce initializers. ConvenIEnce initializers can also fail before performing a self.init() delegation.

总结

以上是内存溢出为你收集整理的ios – 在这个例子中使用隐式解包的可选项有什么意义?全部内容,希望文章能够帮你解决ios – 在这个例子中使用隐式解包的可选项有什么意义?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1048423.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存