LoginSignup
2
1

More than 5 years have passed since last update.

[Swift]ReadLine()のエラーハンドリングと他Datatypeへの変換方法

Last updated at Posted at 2017-09-02

プログラム問題を解いている時に、いろいろ気づいたことをメモリます。
コマンドラインでInputを読み込む時のエラーハンドリングや、キャストが意外と面倒だったので(そして忘れる)、メモで残すことにしました。

ReadLineからString以外のデータタイプに変換する方法

ReadLineは何を入力してもStringとして扱われるので、後で変換したりしないといけないです。例ではStringからDoubleに変換する方法を載せていますが、
StringからInt
StringからFloat
等、どれでもいけます。

方法1:最初に変数を定義しておいて、Inputをキャストする


    var meal:Double!
    var tip:Double!
    var tax:Double!

    let mealCost = readLine()
    let tipPercent = readLine()
    let taxPercent = readLine()

    meal = Double(mealCost!)
    tip = Double(tipPercent!)
    tax = Double(taxPercent!)

    tip = tip * (meal / 100)
    tax = meal * (tax / 100)

    var totalCost = Double(meal) + Double(tip) + Double(tax)

方法2:最初にInputを読み込んで置いて、あとでUnwrapする

    let mealCost = readLine()
    let tipPercent = readLine()
    let taxPercent = readLine()

    guard let convertMeal = Double(mealCost!) else{
        return
    }

    guard let convertTip = Double(tipPercent!) else {
        return
    }

    guard let convertTax = Double(taxPercent!) else {
        return
    }

    let tip = convertMeal * (convertTip / 100)
    let tax = convertMeal * (convertTax / 100)

    let totalCost = convertMeal + tip + tax

    print("The total meal cost is \(Int(totalCost.rounded())) dollars.")

方法3:一番短い

let numStrings = Int(readLine()!)!

実行結果

12.0 // mealCost = readLine()
4 // tipPercent = readLine()
5 // taxPercent = readLine()
The total meal cost is 13 dollars.

ReadLineのエラーハンドリング

下記のサンプルコードでは、InputのデータタイプがIntでなければ、永遠にInputを要求し続けます。


var isInputCorrect = false

while !isInputCorrect{
      print("Input number of computers")

      if let num = readLine(){
            if let convertNum = Int(num){
                 print("right input!")
                 isInputCorrect = true
            } else{
                 print("wrong input, try again")
                 isInputCorrect = false
            }
      }
}

実行結果

Input number of computers // 一回目:アルファベットを入力
f
wrong input, try again
Input number of computers // 二回目: Doubleを入力
4.66
wrong input, try again
Input number of computers // 3回目:正しく Intを入力
4
right input!
2
1
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
2
1