> For the complete documentation index, see [llms.txt](https://lochiwei.gitbook.io/ios/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lochiwei.gitbook.io/ios/swift/input-output.md).

# Input/Output

{% tabs %}
{% tab title="code" %}
💾 程式：replit ⟩ [readLine()](https://replit.com/@pegasusroe/readLine#main.swift)

```swift
// 請使用者輸入資料
// 預設問題：「請輸入一組數字：」
func getInput(from question: String = "請輸入一組數字： ") {

    // 1. 先顯示問題
    print(question, terminator: "")
    
    // 2. 確定輸入是整數
    guard 
        let input = readLine(), // 2.1 先確定有輸入
        let n     = Int(input)  // 2.2 在確定輸入的是整數
    else {
        // 2.3 如果輸入不正確，就顯示警語
        print("拜託❗️請輸入整數好嗎 🙄")
        // 2.4 然後再問一次
        return getInput(from: question)
        // ⭐ 注意：`return` 是必要的，否則會產生：
        // ⛔ error: 'guard' body must not fall through
    }
    
    // 3. 程式如果到這裡，就表示輸入的是整數，而且可以用 n 表示
    print("您輸入的數字是 \(n)")
}

// 執行程式
getInput()

```

{% endtab %}

{% tab title="📘 手冊" %}

* Swift ⟩ Standard Library ⟩ [Input and Output](https://developer.apple.com/documentation/swift/swift_standard_library/input_and_output)
  * [readLine(strippingNewline:)](https://developer.apple.com/documentation/swift/1641199-readline)
    {% endtab %}
    {% endtabs %}
