I have a class called Item with the following properties:
var name: String
var photo: UIImage?
var description: String?
var favorite: Bool
The init method looks like so:
init?(name: String, photo: UIImage?, description: String?,
favorite: Bool) {
guard !name.isEmpty else {
return nil
}
self.name = name
self.photo = photo
self.description = description
self.favorite = favorite
}
In the ViewController, I am trying to instate the variable "item" like so:
var item = Item?
The item is optional because it will only be created if the user pressed the save button. However, there is an error saying "Expected member name or constructor call after type name". I have used the same line with a similar Meal class before without issues.
When I try to create the item using this code:
let name = nameTextField.text ?? ""
let photo = photoImageView.image
let favorite = favoriteButton.favorite
let description = descriptionTextView.text
item = Item(name: name, photo: photo, description: description, favorite: favorite)
An error says "Cannot assign value of type 'Item?' to type 'Item?.Type' (aka 'Optional.Type')". I am new to Swift and unsure what is going on and where the issue is.
Did you mean to declare item
as a member of the class and then instantiate it later? If so,
var item = Item?
should be
var item: Item?
Expected member name or constructor call after type name
means either
var item = Item() // constructor call
or
var item = Item.foo // member name, foo is some type property
To declare an optional without default value you have to write
var item : Item?
Your hybrid form var item = Item?
is not valid syntax.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With