You've got a lot more options then that! Just off the top of my head you could also do:
var value = Float(0)
lazy var value: Float = 1
var value = {0 + 0 as Float}()
Etc, etc. Anyway: I'll assume that this is for instance variables; that isn't clear from your question.
Let's talk about optionals first: you should (if possible) avoid optionals, unless you are dealing with a situation where a value can explicitly be missing; for instance a view that you only instantiate sometimes, or a delegate that isn't always set. In my opinion (and in the opinion of smarter people then me; see github's own Swift Style Guide) you should use implicitly unwrapped optionals (value: Float!
) as little as possible. We see them frequently in Apple's APIs because those APIs are adopted from frameworks that were written in Obj-C, which uses nil differently. The only time something should be an implicitly unwrapped optional is when it can only be set after init
, and when it will never be nil; the place that we see it most frequently is in views that are loaded from storyboard, since this happens just after a view controller is init'd.
For the other patterns: If you don't want to set an initial value, I think that initializing to zero is a good, clear pattern. It is certainly better then using an optional, unless you very specifically want to communicate that this value may not hold any value, at some point in the future.
If you're dealing with something heavier then a float (say an object that is expensive to instantiate) I prefer the lazy
pattern, because if you never access the value until you assign to it it will never be instantiated. There are currently some compiler issues around this, at the moment (XCode 6.1.1), so it might be preferable to use optionals for the time being; lazy
uses optionals behind the scenes, anyway.