Hacker News new | ask | show | jobs
by plus9z 4339 days ago
"For safety, Swift requires the variables to be initialized before being passed with &. This is because it cannot know whether the method being called tries to read from a pointer before writing to it."

I've not written any Swift code yet, so can someone enlighten me -- is this actually true? This seems unnecessarily restrictive (and absurd -- Swift can't tell if a pointer's being read?)

3 comments

If you've got an easy way to tell if a C pointer is being read at compile time I'd certainly like to hear of it, would save quite a bit of valgrinding
If the source to the method being called is not available, then it's certainly possible for the compiler not to be able to tell how a pointer passed to that method might be used.
In the case of an optional it can be initialised to nil (and it will be implicitly).

Swift can tell from static analysis if it might be read at compile time and raise an issue if it isn't initialised on all oaths to the access. If passed as an inout parameter it has to assume it may be read[0] and for safety require that it must be initialised.

[0] at least if it is calling into a library even if it can check the current version it couldn't know for sure that a different library version won't behave differently.