问题描述
let documentUrl: NSURL? = {
return NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first
}
var test: String = {
return "String"
}
这是一段非常简单的代码,但是有错误来自Xcode,让我在计算属性的末尾添加(),如下所示:
This is a very simple piece of code, but there is an error from Xcode, asked me to add () at the end of the computed property, like this:
let documentUrl: NSURL? = {
return NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first
}()
var test: String = {
return "String"
}()
谁能告诉我原因?
推荐答案
您写道:
var test: String = {
return "String"
}
那是 not 计算属性。您正在将变量 test
初始化为函数体(匿名函数,有时称为闭包)。那不是你的意思。您希望调用函数并将变量 test
设置为结果。括号使这种情况发生;这就是你调用一个函数的方式。因此:
That is not a computed property. You are initializing your variable test
to a function body (an anonymous function, sometimes called a closure). That isn't what you mean to do. You want to call the function and set the variable test
to the result. The parentheses make that happen; that is how you call a function. Thus:
var test: String = {
return "String"
}()
因此,您可以一次性定义函数并调用它,并将结果指定为 test 。
Thus you define the function and call it, all in one move, and assign the result as the initial value of test
.
如果你想要一个计算属性,你应该这样写:
If you wanted a computed property, you should have written it like this:
var test: String {
return "String"
}
请注意,没有等号。更全面的形式是:
Notice there is no equal sign. A fuller form would be:
var test: String {
get {
return "String"
}
}
这篇关于函数产生预期类型“String”,你的意思是用“()”调用它吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!