如何在swift中返回一个var [英] how to return a var in swift
本文介绍了如何在swift中返回一个var的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
类ViewController:UIViewController {
var timerVal:Int = calcolo()
func calcolo() - > Int {
return 0;
}
}
但它不起作用。问题是:在调用中缺少参数#1的参数。
解决方案
有两个问题:
- 当调用一个实例方法来初始化一个属性时,必须明确指定实例,即
self
- 因为
self $>,因此不能使用语句或表达式直接或间接引用
self
来初始化实例属性。在所有属性初始化之前,c $ c>不可用
要解决此问题,可以将属性声明为 lazy
- 它会在第一次被访问时被初始化,所以在实例初始化之后:
lazy var timerVal:Int = self.calcolo()
I'm so confused because I'm habituated to get a var by function like this:
class ViewController: UIViewController {
var timerVal:Int = calcolo()
func calcolo() -> Int {
return 0;
}
}
But it don't work. The problem is: Missing argument for parameter #1 in call.
解决方案
There are 2 problems:
- when invoking an instance method to initialize a property, you have to explicitly specify the instance, i.e.
self
- an instance property cannot be initialized with a statement or expression directly or indirectly referencing
self
, becauseself
is unavailable until all properties have been initialized
To fix the problem you can declare the property as lazy
- it will be initialized the first time it is accessed, so after the instance initialization:
lazy var timerVal:Int = self.calcolo()
这篇关于如何在swift中返回一个var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文