Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

swift - Pattern match and conditionally bind in a single Switch statement

Is there a way to write this if/else if/else ladder as a switch statement?

let x: Any = "123"

if let s = x as? String {
    useString(s)
}
else if let i = x as? Int {
    useInt(i)
}
else if let b = x as? Bool {
    useBool(b)
}
else {
    fatalError()
}

Here's my attempt:

switch x {
case let s where s is String:   useString(s)
case let i where i is Int:      useInt(i)
case let b where b is Bool:     useBool(b)
default: fatalError()
}

It successfully chooses the right path, but s/i/b are still of type Any. The is check doesn't have any effect in casting them. This forces me to force cast with as! before usage.

Is there a way to switch on the type, and bind it to a name, all in one switch statement?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Sure, you can use the conditional casting pattern case let x as Type:

let x: Any = "123"

switch x {
case let s as String:
    print(s)   //use s
case let i as Int:
    print(i)   //use i
case let b as Bool:
    print(b)   //use b
default:
    fatalError()
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...