0

From an API design standpoint, it seems to me that the use of Implicitly Unwrapped Optional (IUO) in method signature only benefits the method code (to not have to unwrap) instead of the caller.

Take this open source code for example:

class func getStationDataWithSuccess(success: ((metaData: NSData!) -> Void)) {

        if useLocalStations {
            getDataFromFileWithSuccess() { data in
                success(metaData: data)
            }
        } else {
            loadDataFromURL(NSURL(string: stationDataURL)!) { data, error in
                if let urlData = data {
                    success(metaData: urlData)
                }
            }
        }
    }

I see no value in metaData being declared as an IUO when it can be optional, or is there a reason why this method parameter should be declared as such?

Therefore, from an API design standpoint, it seems to me that Optional should always be a better practice over IUO (based on concrete reasons, not opinions)

Boon
  • 40,656
  • 60
  • 209
  • 315
  • Not quite a duplicate (you are asking about parameters in methods), but related: http://stackoverflow.com/questions/24006975/why-create-implicitly-unwrapped-optionals – Steve Wilford Oct 13 '15 at 10:35
  • Thanks @SteveWilford. If you look through the answer, you will see that none mentions why in a normal API, as shown in the example code that IUO is better than Optional. – Boon Oct 13 '15 at 10:43

1 Answers1

0

In terms of API design, I believe the accepted answer here also answers your question for the most part:

In Swift, what does the ! symbol mean in a function signature?

Additionally, some good general use cases and motivations for implicitly unwrapped optionals can be found in the first few answers here:

Why create "Implicitly Unwrapped Optionals"?

Community
  • 1
  • 1
Dennis G.
  • 283
  • 1
  • 11
  • I read both before posting this. They talked about ObjC bridging and such, but does not answer why optional is not better than IUO in a normal API design. – Boon Oct 13 '15 at 10:41
  • I don't think IUO is better in normal API design, but rather in the context mentioned in the first answer above, however I will look into it a little more and try to come up with a better answer. – Dennis G. Oct 13 '15 at 10:52
  • I really don't think there is any good reason for using an IUO in a method signature asides from interoperability. The open source API you linked has no use for it in its method signature and will function identically without being implicitly unwrapped. More info on interoperability: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/BuildingCocoaApps/InteractingWithObjective-CAPIs.html – Dennis G. Oct 13 '15 at 11:11