LoginSignup
0
0

More than 5 years have passed since last update.

Swift コマンドラインから文字列を取得する

Last updated at Posted at 2017-10-14

環境

  • Xcode9.0
  • macOS High Sierra 10.13
  • CommandLineTool

スペース区切りで型が異なる入力がされた場合

nilを除く配列取得

func readLineArrayWithoutNil<T: LosslessStringConvertible>() -> [T] {
    return readLine()!.split(separator: " ").flatMap{ T.init(String($0)) }
}

nilを含む配列取得 (入力数が知りたい場合など)

func readLineArrayIncludeNil<T: LosslessStringConvertible>() -> [T?] {
    return readLine()!.split(separator: " ").map{ T.init(String($0)) }
}

実行結果

入力 "1 a 1.125"

let ints: [Int] = readLineArrayWithoutNil() 
// [1]

let ints: [Double] = readLineArrayWithoutNil() 
// [1.0, 1.125]

let ints: [String] = readLineArrayWithoutNil() 
// ["1", "a", "1.125"]
let ints: [Int] = readLineArrayIncludeNil() 
// [Optional(1), nil, nil]

let ints: [Double] = readLineArrayIncludeNil() 
// [Optional(1.0), nil, Optional(1.125)]

let ints: [String] = readLineArrayIncludeNil() 
// [Optional("1"), Optional("a"), Optional("1.125")]

コマンドラインの入力を1文字ずつStringで取得するには

readLine()!.flatMap{ String($0) }

実行結果

入力 "1 a 1.125"

readLine()!.flatMap{ String($0) } 
//["1", " ", "a", " ", "1", ".", "1", "2", "5"]

おまけ

readLineArrayの関数を作っていて、編集後コンパイルすると初回だけ出力がおかしい時がありました。Xcodeのバグだろうか。
再度コンパイルするとうまくいきます(謎

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0