Swift对象永远无法在其中投入价值 [英] Swift Object never able to put value inside it

查看:67
本文介绍了Swift对象永远无法在其中投入价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为MovieMovie的名为newMovieVar的对象. 下面有对象声明.

I have an object named newMovieVar of type Movie. Below I have the object declaration.

import Foundation

class Movie: NSObject {
var moviePoster: String = ""
var movieName: String = ""
}

在使用此对象的视图控制器中,我这样声明它:

In the view controller where I use this object, I declare it like this:

 var newMovieVar: Movie!

然后我尝试在其中设置值

And then I try to set values in it

newMovieVar?.moviePoster = "bla bla"
newMovieVar?.movieName = "bla bla bla"

但是每当我尝试从newMovieVar打印值时,我都会得到 nil :

But whenever I try to print the values from newMovieVar, I get nil:

print(newMovieVar?.moviePoster)
print(newMovieVar?.movieName)

你知道为什么吗?

推荐答案

您正在声明类型为Movie的变量,但没有给它赋值.您需要创建一个新的Movie对象并将其分配给您的变量,以便有一个供您使用的值.

You are declaring a variable of type Movie but you are not giving it a value. You need to create a new Movie object and assign it to your variable so there is a value for you to work with.

var newMovieVar = Movie()

这篇关于Swift对象永远无法在其中投入价值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆