What does this mean? Variable declared followed by a block without assignment

前端 未结 3 1948
梦毁少年i
梦毁少年i 2021-01-25 12:54

Noob Swift question--I can\'t figure out what this means in Swift:

public var currentTime: NSTimeInterval? {
    return self.audioPlayer?.currentTime
}


        
相关标签:
3条回答
  • 2021-01-25 13:42

    This is called Read-Only Computed Properties

    According to Apple Docs

    A computed property with a getter but no setter is known as a read-only computed property. A read-only computed property always returns a value, and can be accessed through dot syntax, but cannot be set to a different value.

    For more info Computed Properties

    0 讨论(0)
  • 2021-01-25 13:43

    It is the same as:

    public var currentTime: NSTimeInterval? {
        get { return self.audioPlayer?.currentTime }
    }
    

    When your computed property only has a get, you can omit the word get and the curly brackets.

    From the swift guide:

    You can simplify the declaration of a read-only computed property by removing the get keyword and its braces:

    0 讨论(0)
  • 2021-01-25 13:49

    I wrote a little playground for clarification:

    //: Computed properties
    
    import UIKit
    
    var variable_int = 1
    
    var computed_int: Int {
    get { return 1 }
    set { newValue }
    }
    
    var get_only_int: Int {
      return 1
    }
    
    var get_only_int_2: Int {
    get { return 1 }
    }
    
    variable_int = 2 // legal
    computed_int = 2 // legal
    
    // computed_read_only_int = 2   // 'computed_read_only_int' is a get-only property
    // computed_read_only_int_2 = 2 // 'computed_read_only_int_2' is a get-only property
    
    
    // This is another way to specify a variable you could find useful, I found it somewhere on natashatherobot.com
    var variable_int_2: Int = {
      return 1
    }()
    
    variable_int_2 = 2 // legal
    

    works in Xcode 8.1

    0 讨论(0)
提交回复
热议问题