[swift-evolution] Optionals and nil in Switch statement

Lucas Jordan lucasjordan at gmail.com
Tue Jun 28 11:52:01 CDT 2016


This is sort of weird right? because comparing nil to a non nil string is a
reasonable thing to do:

var nilString:String? = nil

if nilString == "this always fails" {}

is totally reasonable.

On Tue, Jun 28, 2016 at 12:33 PM, Kevin Nattinger <swift at nattinger.net>
wrote:

> No
>
>   7> switch str {
>   8. case "foo": print("case foo")
>   9. case .none: print("(nil)")
>  10. }
> error: repl.swift:8:6: error: value of optional type 'String?' not
> unwrapped; did you mean to use '!' or '?'?
> case "foo": print("case foo")
>      ^
>           !
> Odd error, but at least it suggests it’s an issue with optionaity.
>
>
> On Jun 28, 2016, at 9:27 AM, Nevin Brackett-Rozinsky <
> nevin.brackettrozinsky at gmail.com> wrote:
>
> Does `case "text"?` work?
>
>
> On Tuesday, June 28, 2016, Kevin Nattinger via swift-evolution <
> swift-evolution at swift.org> wrote:
> Case .none:
> Case .some("string"):
>
>
> On Jun 28, 2016, at 06:40, Lucas Jordan via swift-evolution <
> swift-evolution at swift.org> wrote:
>
> Forgive me if this was/is discussed already, I am new to the process
> here....
>
> (code is attached as a playground too)
>
>
>
> Sometimes when I am working with a String? nil can be a reasonable value,
> and what I want to do is something like the following:
>
> import UIKit
>
>
>
> var str:String? = "Hello, playground"
>
>
>
> switch str{
>
> case nil:
>
>     print("Nil!")
>
> case "Hello, playground":  //it would be super nice if this worked.
>
>     print("Match")
>
> default:
>
>     print("Some other non nil value?")
>
> }
>
>
>
> But it does not work, the orange  text is a compile time error,
> "Expression pattern of type 'String' cannot match value of type 'String?'.
> I realize that this can be replaced with a let statement
> (case let s where s == "Hello, playground":), but that is verbose.
>
> Seems like the compiler could be OK with the orange text, since it is
> clearly not nil.
>
> Thoughts?
>
> -Lucas
>
>
>
>
>
> <NilInSwitchStatements.playground.zip>
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160628/91ee39c7/attachment.html>


More information about the swift-evolution mailing list