2016-08-16 5 views
3

switch文としてif/else if/elseラダーを記述する方法はありますか?1つのSwitchステートメントでパターンマッチし、条件付きでバインドする

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() 
} 

ここに私の試みです:

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() 
} 

それが正常に正しい道を選択したが、s/i/bはタイプAnyではまだです。 is小切手は、キャストに影響を与えません。これにより、使用前に強制的にキャストされてas!になります。

種類を入れ替えて名前にバインドする方法はありますか?switchステートメント?

+0

あなたがやっていることは正しいが、各 'case'ための実行文が欠落しています。 'print'を追加するだけでエラーは見えません。 – Santosh

+0

はい、それはエラーですが、デモンストレーションのために省略しました。 'print(_ :)'は 'Any'型のパラメータを扱う際には問題ありません。 '// use s'のようなコメントが実際に' String'/'Int' /' Bool'型のパラメータを取る関数呼び出しであるとします。 – Alexander

+0

@サントシュ私は私の質問を明確にしました。 – Alexander

答えて

7

確かに、あなたは使うことができconditional casting patterncase 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() 
} 
+0

これはまさに私が探していたものです。私は5分で受け入れるよ – Alexander

+0

@AlexanderMomchliov喜んで:) – Hamish

関連する問題