Function produces expected type “String”, did you mean to call it with “()”

前端 未结 1 1216
逝去的感伤
逝去的感伤 2021-01-26 13:35
let documentUrl: NSURL? = {
    return NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first
}

var test: String = {
             


        
相关标签:
1条回答
  • 2021-01-26 14:15

    You wrote this:

    var test: String = {
        return "String"
    }
    

    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"
    }()
    

    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"
        }
    }
    
    0 讨论(0)
提交回复
热议问题