简体   繁体   English

在Swift 3中使用默认初始化器更改可选属性值

[英]Changing a optional property value with the use of a default initializer in Swift 3

What is wrong with the line of code when I set the variable called item2 and why isn't this initialization possible to do if the name property is optional? 当我设置名为item2的变量时,代码行有什么问题?如果name属性是可选的,为什么不能进行这种初始化?

class ShoppingListItem {
    var name: String?
    var quantity = 1
    var purchased = false
}

var item = ShoppingListItem()
var item2 = ShoppingListItem(name:"Orange Juice")

print(item.name)
print(item2.name)

With this code 有了这个代码

ShoppingListItem(name:"Orange Juice")

you are invoking an initializer of ShoppingListItem that does not exist. 您正在调用不存在的ShoppingListItem的初始化程序。

So just define the initializer into the class 因此,只需将初始化程序定义到类中

class ShoppingListItem {
    var name: String?
    var quantity = 1
    var purchased = false

    init(name:String) {
        self.name = name
    }

    init() { }
}

Memberwise Initializers for Structure Types 结构类型的成员初始化器

Structure types automatically receive a memberwise initializer if they do not define any of their own custom initializers. 如果结构类型未定义任何自己的自定义初始化程序,则它们会自动接收一个成员初始化程序。 Unlike a default initializer, the structure receives a memberwise initializer even if it has stored properties that do not have default values. 与默认初始化程序不同,该结构即使在存储了没有默认值的属性的情况下,也会接收成员初始化程序。

The memberwise initializer is a shorthand way to initialize the member properties of new structure instances. 逐成员初始化器是初始化新结构实例的成员属性的简便方法。 Initial values for the properties of the new instance can be passed to the memberwise initializer by name. 可以通过名称将新实例的属性的初始值传递给成员初始化器。

The example below defines a structure called Size with two properties called width and height. 下面的示例定义了一个名为Size的结构,具有两个名为width和height的属性。 Both properties are inferred to be of type Double by assigning a default value of 0.0. 通过指定默认值0.0,可以推断两个属性均为Double类型。

The Size structure automatically receives an init(width:height:) memberwise initializer, which you can use to initialize a new Size instance: Size结构自动接收一个init(width:height :)成员初始化器,您可以使用该初始化器初始化一个新的Size实例:

struct Size {
    var width = 0.0, height = 0.0
}

let twoByTwo = Size(width: 2.0, height: 2.0)

In your code you have to add initializer, or set a name after initialization: 在代码中,您必须添加初始化程序,或在初始化后设置名称:

class ShoppingListItem {
    var name: String?
    var quantity = 1
    var purchased = false
}

var item2 = ShoppingListItem()
item2.name = "Orange Juice"

print(item2.name)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM