Swift 4.2, Xcode 10.2 nil coalescing operator warning

Ravi Sisodia

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 ?

Bram

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Nil Coalescing Operator Swift

Swift nil coalescing operator with array

Nil coalescing operator for dictionary

Coalescing Swift operator for an empty non-nil string

swift nil coalescing with doubles

Nil Coalescing Operator with mixed types

Why is the nil coalescing operator ?? returning nil?

Why doesn't Swift nil-coalescing ternary operator return unwrapped type?

Compiler not understanding Nil Coalescing Operator on NSTimeInterval

Nil-Coalescing Operator without changing value

Swift 2 Nil Delegate

Why is Swift nil-coalescing returning an Optional?

Null-coalescing assignment operator in Swift 3

Using nil-coalescing operator with try? for function that throws and returns optional

What is the role of the nil-coalescing operator "??" in optional chaining?

Why does the nil coalescing operator wrap an implicitly unwrapped default value?

NSDateFormatter returns nil in swift 2

Swift 2 unused constant warning

Converting String value from UILabel to Int returns nil | Swift 2 / Xcode 7

Xcode 7.3 / Swift 2: "No method declared with Objective-C selector" warning

Swift 4 - OpenCV 3.2 on Xcode 9.0 beta 2

Is Nil-Coalescing always needed when using firstIndex(of: Character) in Swift?

Swift: compile-time error with optional chaining and nil-coalescing

How to remove XCode9 "Conversion to swift 4 is available" warning?

binary operator '==' cannot be applied to operands of type 'String!' and '[String]' in Swift 2 Xcode 7

Swift 2, Xcode 7.2 'NSInternalInconsistencyException

TouchID with Xcode 7, Swift 2

Populating UICollectionView with images is returning nil : Swift 2

Swift 2 : NSData(contentsOfURL:url) returning nil