やりたかったのはRubyで言う下のような事です。
num = 1 str = case num when 1 then 'one' when 2 then 'two' end
下のlet str: String
みたいな宣言だけするのが嫌だった事がきっかけで調べ始めました。
宣言だけって代入漏れが起きそうで気持ち悪いので避けたいと思ってます。
let num = 1 let str: String switch num { case 1: str = "one" case 2: str = "two" }
普通にRubyっぽく書くのはダメ。
ググってもそれらしき情報は見つかりませんでした。
// これはエラー let a = 1 let num = switch a { case 1: "one" case 2: "two" }
Swiftはenumがメソッドを持つのでenum化できるものは下のように対処しようと思います。
enum Num { case One case Two func str() -> String { switch self { case .One: return "one" case .Two: return "two" } } } let a = Num.One let num = a.str()