Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: Cannot assign value of type 'Item?' to type 'Item?.Type'

Tags:

class

ios

swift

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.

like image 635
Meowgan Avatar asked Feb 24 '17 21:02

Meowgan


2 Answers

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?
like image 185
Samantha Avatar answered Nov 15 '22 22:11

Samantha


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.

like image 29
vadian Avatar answered Nov 15 '22 22:11

vadian