Noob Swift question--I can\'t figure out what this means in Swift:
public var currentTime: NSTimeInterval? {
return self.audioPlayer?.currentTime
}
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
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:
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