0

On Xcode 10.1, the following statement wasn't having any issues, but after updating the Xcode to 10.2 compiler is generating warning for the statement.

return [
    "sublevels": (self.sublevels?.array ?? [Sublevel]()) as NSObject
]

sublevels is NSOrderedSet, and the warning generated is as follows:

Left side of nil coalescing operator '??' has non-optional type '[Any]?', so the right side is never used

But if I break the single statement as follows, the warning disappears.

let sublevels = self.sublevels?.array ?? [Sublevel]()
return [
    "sublevels": sublevels as NSObject
]

Please, will anyone explain - what is the issue with the first statement ?

Ravi Sisodia
  • 776
  • 1
  • 5
  • 20
  • 2
    A (minimal) *self-contained* compiling example would be helpful. – Martin R Apr 08 '19 at 07:43
  • 2
    I think the error message should be reported as a bug. `[Any]?` definitely is an Optional. But you need to supply some `[Any]` as the left hand side of `??` is of type `[Any]?`. What if you replace `?? [Sublevel]()` to `?? []` ? – OOPer Apr 08 '19 at 08:01
  • I wouldn't say it's a bug, regarding the [SE-0054](https://github.com/apple/swift-evolution/blob/master/proposals/0054-abolish-iuo.md) rules. `Any` is optional, as long as `Any` has no type basically. – Bram Apr 08 '19 at 08:06
  • @Craz1k0ek, SE-0054 is describing about ImplicitlyUnwrappedOptional, and `[Any]?` aka `Optional>` is a normal Optional and nothing described in SE-0054 applies to normal Optional. Are you mistaking with some other proposal? – OOPer Apr 08 '19 at 08:45
  • @OOPer ah yeah, you’re right. Was a bit quick. Better would be to link to [type casting](https://docs.swift.org/swift-book/LanguageGuide/TypeCasting.html) – Bram Apr 08 '19 at 09:09

1 Answers1

1

As mentioned by OOPer, the solution is to provide a default Any value as right hand side of the operator, in this case an [Any], because the NSOrderedSet has no specific type bound to it. The solution is:

return [
    "sublevels": (self.sublevels?.array ?? []) as NSObject
]

For more info on this matter I suggest you take a look at type casting. At the bottom of the page there is an explanation about casting the Any type.

Bram
  • 2,718
  • 1
  • 22
  • 43