user6510422 user6510422 - 4 months ago 8
Swift Question

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?

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


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)

Answer

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