General problem with Optional types as generics?

I’m encountering lots of problems using generics with optional types. For example:

class Bar<T> {
    var value: T
    init(_ value: T) { self.value = value }
}

let b: Bar<Int?> = Bar(nil) // Error: Cannot assign null to-non-nullable

Do I need to just avoid those for now or is there a subset of issues that can be described and worked around?

For now avoid those. This is one of those tricky things that don’t map well to .NET/Java. I haven’t found a great solution yet for them.

Thanks for getting back to me, Carlo.

Here is a hack that I have been using to work around this issue on Elements version 9.2 with Silver on .NET:

class Bar<T> {
    var value: T?
    init(_ value: T?) { self.value = value }
}

let b: Bar<Int?> = Bar<Int?>(nil)

You might think this results in value being an “optional optional”, but the compiler doesn’t appear to treat it that way. Instead, it seems to do what you were looking for in the original post.

You can also use the same class with non-optionals like this:

let a: Bar<Int> = Bar<Int>(1234)

but you may need to perform some forced unwrapping of ‘value’ depending on how you use it.

I’m using this hack on cross-platform code between .NET and macOS. With the Apple compiler, value becomes an “optional optional” instead of just an “optional”, so it also requires some extra unwrapping. But with some fiddling, I have successfully created code that runs without modification on both platforms.

Overall, it’s pretty ugly though because the code doesn’t accurately represent what appears to be generated by the Elements compiler.

Any update on when/if this functionality might be properly implemented?

1 Like

Just ran across this issue. Also wondering if that’s on the todo list (will look at shawnd’s workaround in the mean time).