I'm trying to convert my Swift 3 code to Swift 4. I get this error message:
Expression pattern of type 'String' cannot match values of type 'NSStoryboardSegue.Identifier
This is my code:
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
switch segue.identifier {
case "showVC1":
// DO SOMETHING
break
default:
break
}
}
Which type should I use instead of "String"?
As of Swift 4, the storyboard identifier is a optional
NSStoryboardSegue.Identifier
, which is defined asYou can switch on its
rawValue
:The recommended pattern however is to define constants for each storyboard identifier:
which can then be matched against:
In both examples, the "optional pattern"
x?
(a shortcut for.some(x)
) is used to match against an optional value.Similar types were introduced for other "identifiers", e.g.
NSImage.Name
, which is the argument type ofNSImage(named:)
in Swift 4.For more information, see the discussion on the swift-users mailing list, starting at
The general idea (as I understand it) is to create separate types for each kind of identifier. In particular (from https://lists.swift.org/pipermail/swift-users/Week-of-Mon-20170717/005940.html):
Swift 4 switched the type of
identifier
property fromString?
toNSStoryboardSegue.Identifier?
. The type isRawRepresentable
,RawType
ofString
. You may need to change your code to a chain ofif
statements, or userawValue
explicitly: