I am using code where its like
let date: NSDate? = {
return nil
}()
what does it mean when you type () at end of the code.
Is that getter?
I am using code where its like
let date: NSDate? = {
return nil
}()
what does it mean when you type () at end of the code.
Is that getter?
That’s a closure. You’ve basically written a long form of this:
let date: NSDate? = nil
The {}
forms a closure around the instruction “return nil
”. The ()
calls the closure, and Swift infers the closure’s arguments - it has none - from this; it infers the return type - NSDate?
- from the declaration of the variable (date
) you’re assigning the result of the closure to.
Getters and setters are about allowing enough access to your types (structs / classes etc.) to read useful information and allow useful configuration while hiding unnecessary detail and preventing you from accidentally making our types inconsistent. For example, count
on an Array is a getter; you can call array.count
and get a numerical value, but you can’t set the count of an array, and you wouldn’t want to.
Here’s one way you could write code to let someone get and set a value of type NSDate
, so long as that date was before right now:
private var privateDate : NSDate = NSDate() // initialised to right now; hidden outside of the type.
var date : NSDate
{
get { return privateDate }
set {
if newValue.compare(NSDate()) == NSOrderedAscending {
privateDate = newValue
}
}
}
Thanks for the reply. It did actually help me a lot. Sorry for late reply.