0

I'm confused about the type requirements and declaration restrictions for Swift capture specifiers. The documentation says that weak references must be var and "of optional type", and that unowned references must be of non-optional type. But Apple's own API reference has examples of unowned(unsafe) references declared as optionals, while the Xcode interface builder creates weak outlets and actions that are implicitly unwrapped (which is not always clearly "of optional type" in the language reference).

What types are required for each of the Swift capture specifiers? Which must be var and which can be let?


FWIW, I think its

  • weak can be Type? or Type!, but not Type; and must be var
  • unowned(safe) (same as unowned) must be Type; and may be let
  • unowned(unsafe) can be Type? or Type!; and may be let

but I'm far from sure.

Community
  • 1
  • 1
orome
  • 45,163
  • 57
  • 202
  • 418

1 Answers1

0

First the Cocoaor Cocoa touch APIs are imported in swift fromobjective-c`. They are mapped in swift with best possible ways.So that both can interoperable.

Those unowned(unsafe) properties are marked as assign in ObjC. These are unsafe and ARC doesn't retain the object, and it doesn't make sure the reference gets reset to nil if the object is deallocated. These are old apple API and not changed with ARC and remain asassignbut you should makedelegateweak` Do not look for headers for best practices in swift they have made many tricks to make swift and objective-c interoperable and if you do what headers do than you loose all safety swift proveide.

You are right

weak should be optional as contain nil automatically if objects get deallocate and no other pointer retain it

unowned(safe) should not be optional and will not reset to nilif objects deal-located

unowned(unsafe) can or can not be optional as it not provide any safety by ARC for object deal-location and do not reset to nil.You should not use this in swift program.Use unowned if needed.It is just for interoperability.

weak is always var because it can be changed when objects deallocate and set to nil.

unowned(safe) and unowned(unsafe) can be both var or let as they are dependent on you and run-time will not change these variables.

Note:You can not declare a unowned(unsafe) as optional in swift program.Its for just interoperability and should not be used in swift.They have made this because of assign or unretain properties can be nil

codester
  • 36,891
  • 10
  • 74
  • 72
  • It isn't clear how this maps to the question (or my guess at an answer). Can you focus/clarify? – orome Oct 25 '14 at 17:04
  • @raxacoricofallapatorius please let me know which parts need clarification. – codester Oct 25 '14 at 17:09
  • Thanks, that's much better. If you could condense a bit (e.g. follow the structure of my FWIW, which say about the same thing though much more clearly). – orome Oct 25 '14 at 17:31