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

hyouuu

I read that the ternary operator ?? unwraps an optional if it is not nil, but if I do:

var type: String?
type = "milk"
let certainType = type ?? "melon"

then certainType will still be a String?, and if I do

println("it's a \(certainType)")

it will print:

it's a Optional("milk")

Thoughts?

Update:

Sorry for the confusion - I meant var type: String?

I get that it should print "it's a milk", but what I saw in console is a "it's a Optional("milk")" - anyone else experienced the same issue? Could that be caused by string interpolation?

Asked by @Antonio, here is more context and real code and logging snapshot - type is from Note, which is a NSManagedObject class used to deal with xcdatamodel

class Note: NSManagedObject {
  @NSManaged var type: String?
}

And I have the type set to 'todo' at some point, then have the following code to print them out:

println("type class:\(_stdlib_getDemangledTypeName(note.type))")
let type1 = note.type ?? "note"
println("type1:\(type1)")
let type2: String = note.type ?? "note"
println("type2:\(type2)")

And the output:

type class:Swift.Optional
type1:Optional("todo")
type2:todo

As you can see, if I don't explicitly mark the type1's type as String, it will print undesired result Optional("todo") - I use the type in a string interpolation to construct a path so it matters

Antonio

I can't prove what I am going to say, so any feedback is very well appreciated.

The OP asserts that code similar to this:

var type: String? = "milk"
let certainType = type ?? "melon"
println("it's a \(certainType)")

prints an unexpected string:

"it's a Optional("milk")"

whereas it should be:

"it's a milk"

It turns out that happens when the variable is actually a property with the @NSManaged attribute.

I suspect that there is a bug in type inference. The OP states that:

let certainType = type ?? "melon"

prints the wrong result, whereas:

let certainType: String = type ?? "melon"

prints the correct one.

So for some reason, without explicitly indicating the variable type, the nil coalescing operator is returning an optional.

If I change the type of the type variable to either AnyObject or AnyObject?, it actually prints the unexpected result:

var type: AnyObject = "milk"
let certainType = type ?? "melon"
println("it's a \(certainType)")

"it's a Optional(milk)"

My guess is: because the @NSManaged attribute is used, the property is inferred with the wrong type (AnyObject?) when used, unless the correct type is explicitly indicated.

As to why that happens, no idea (besides thinking it's a bug)

Feel free to up or down vote this answer, and most important don't consider it as a solution - I would appreciate feedback though, because I'm curios to know what's going on and whether it's really a bug or not.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Why can't we have return in the ternary operator?

Why doesn't Java allow the use of a ternary operator here?

Why doesn't the ternary operator like generic types with bounded wildcards?

Why doesn't this method work? Java ternary operator

Why Go doesn't have a ternary conditional operator

How is the return type of a ternary operator determined?

PHP ternary operator vs null coalescing operator

Return type of '?:' (ternary conditional operator)

Why doesn't the C# ternary operator work with delegates?

Coalescing Swift operator for an empty non-nil string

Why is a Swift implicitly unwrapped optional `nil`?

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

Why is Swift nil-coalescing returning an Optional?

Why is the nil coalescing operator ?? returning nil?

Why doesn't PHP's null coalescing operator (??) work on class constants with different visibilities?

Null coalescing operator (??) with return

Swift nil coalescing operator with array

Why ternary operator doesn't replace if-else

Why doesn't this type guard work in this ternary expression?

Why the below code works using swift ternary operator but doesn't work using if else

Nil coalescing operator for dictionary

Nil Coalescing Operator Swift

Why doesn't guard create unwrapped var?

Nil Coalescing Operator with mixed types

Why Ternary Operator doesn't work with using 'hasClass'?

Swift 4.2, Xcode 10.2 nil coalescing operator warning

swift nil coalescing with doubles

Ternary operator doesn't return react component

C++ trivial function: return value type doesn't match the function return type: ternary operator

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive