[英]Swift: Cannot assign value of type 'Item?' to type 'Item?.Type'
I have a class called Item with the following properties: 我有一个名为Item的类,它具有以下属性:
var name: String
var photo: UIImage?
var description: String?
var favorite: Bool
The init method looks like so: init方法如下所示:
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: 在ViewController中,我试图像这样设置变量“item”:
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.
我之前使用过相同的Meal类相同的行没有问题。
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')".
输入'Item?.Type'(又名'Optional.Type')“。 I am new to Swift and unsure what is going on and where the issue is.
我是Swift的新手,不确定发生了什么以及问题出在哪里。
Did you mean to declare item
as a member of the class and then instantiate it later? 你的意思是声明
item
作为类的成员然后稍后实例化它? 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?
你的混合形式
var item = Item?
is not valid syntax. 是无效的语法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.