Laurence Wingo
Laurence Wingo

Reputation: 3952

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)

Upvotes: 0

Views: 477

Answers (3)

Igor
Igor

Reputation: 12303

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)

Upvotes: 1

Luca Angeletti
Luca Angeletti

Reputation: 59496

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() { }
}

Upvotes: 3

Asdrubal
Asdrubal

Reputation: 2461

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)

Upvotes: 1

Related Questions