本文介绍了在 Swift 中初始化类实例和访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我刚刚创建了一个类并给了它一些变量.不幸的是,我无法在我的 iOS-Projects
中访问这些变量.但是,相同的语法在操场上也有效...
I just created a class and gave it some vars. Unfortunately I can't access these variables in my iOS-Projects
. However, the same syntax works in playground...
class ViewController: UIViewController
{
class Dog
{
var age = 0
var hungry = TRUE
}
var rex = Dog()
rex.age = 2 //ERROR: EXPECTED DECLARATION
}
推荐答案
类声明的语法是:
class <class name>: <superclass>, <adopted protocols> {
<declarations>
}
您对 ViewController
的声明包括 rex.age = 2
,它本身不是一个声明,而是一个声明 - 特别是带有中缀运算符的二元表达式.
Your declaration of ViewController
includes rex.age = 2
which itself is not a declaration, it is a statement - specifically a binary expression with an infix operator.
这篇关于在 Swift 中初始化类实例和访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!