简体   繁体   中英

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?

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.

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. Both properties are inferred to be of type Double by assigning a default value of 0.0.

The Size structure automatically receives an init(width:height:) memberwise initializer, which you can use to initialize a new Size instance:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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