4
votes

Is the idea of Swift's "implicitly unwrapped optionals" the same as Java's "autoboxing" of integers? The following runtime exception would only be possible in Swift if xObj is declared an "implicitly unwrapped option":

Integer xObj = new Integer(-1);  
xObj = null;  // could do this with an implicitly unwrapped optional as well.
Integer.valueOf(xObj); // <-- exception. Integer.valueOf(int x); couldn't deal with this.

The point being that "implicitly unwrapped optionals" CAN be nil, but you better be careful and not use them when a non-nil reference is expected, right?

1

1 Answers

2
votes

Is the idea of Swift's "implicitly unwrapped optionals" the same as Java's "autoboxing" of integers?

Same? No. That's too strong of a statement. Serve a similar purpose, in some cases? Yes.

Autoboxing is used in Java for 2 main reasons:

  1. To convert value types (the primitives) to objects, so that they can be stored in collections, like ArrayList and HashMap.

    • The only primitives that need this treatment are byte, short, int, long, float, double, boolean, and char. Hence why those are the only types with auto-box object equivalents. Java autoboxing is limited to only these types, whereas in Swift, Optionals are applicable to all types.
    • Swift's native collections can store value types, so this conversion isn't necessary.
    • Foundation's collections can only store pointers. When using them, Swift does a similar thing as Java, by automatically boxing numerical types into NSNumber objects.
    • Swift's Optional is an enum, a value type, regardless of whether it's wrapping a reference type or a value type.
  2. Allow for nullability without using a sentinel value. I.e. returning null instead of -1, Integer.MIN, etc.

    • This is the what Swift's Optionals are for.