Swift教室 Swift と競技プログラミングの教室

コンパイルエラー集

読了目安 約3分

よく出るエラーメッセージ 10 個を、原因と直し方つきで引ける。

この章の目次

エラーが出たら、この章をメッセージで検索してください。 コンパイルエラーは実行前にコンパイラが見つけた間違い、実行時エラーは実行の途中でプログラムが止まる間違いです。

実際のメッセージの先頭には main.swift:2:14: のような場所情報が付きます。 数字は「2 行目の 14 文字目」という意味なので、まずその行を見てください。

cannot find ‘x’ in scope

テキスト
error: cannot find 'x' in scope
Swift
print(x)

x という名前が、その場所からは見つからないという意味です。 名前の打ち間違いか、定義する前に使っているのが典型です。 綴りを確認し、let x = ... のような定義を使う行より前に書いてください。

cannot convert value of type ‘String’ to specified type ‘Int’

テキスト
error: cannot convert value of type 'String' to specified type 'Int'
Swift
let s = "42"
let n: Int = s

Int と宣言した場所に文字列を入れようとしています。 見た目が数字でも、"42" は文字列です。 let n: Int = Int(s)! のように変換してください。

value of optional type ‘String?’ must be unwrapped

テキスト
error: value of optional type 'String?' must be unwrapped to a value of type 'String'
Swift
let line: String = readLine()

readLine() が返すのは String ではなく、オプショナルの String? です。 競プロでは入力が必ずあるとみなし、readLine()!! を付けて使います。

binary operator ‘+’ cannot be applied (‘String’ と ‘Int’)

テキスト
error: binary operator '+' cannot be applied to operands of type 'String' and 'Int'
Swift
let line = readLine()!
let n = line + 1

読み込んだ入力を、文字列のまま計算に使っています。 let n = Int(line)! + 1 のように、先に整数へ変換してください。

binary operator ‘+’ cannot be applied (‘Int’ と ‘Double’)

テキスト
error: binary operator '+' cannot be applied to operands of type 'Int' and 'Double'
Swift
let a = 3
let b = 1.5
print(a + b)

Swift は IntDouble を自動では混ぜてくれません。 Double(a) + b のように、どちらかの型へそろえてから計算してください。

cannot assign to value: ‘x’ is a ’let’ constant

テキスト
error: cannot assign to value: 'x' is a 'let' constant
Swift
let x = 1
x = 2

let で作った定数に、あとから代入しようとしています。 書き換えたい値は var x = 1var で宣言してください。

cannot convert value of type ‘String.SubSequence’

テキスト
error: cannot convert value of type 'String.SubSequence' (aka 'Substring') to expected argument type 'String'
Swift
let parts = readLine()!.split(separator: " ")
var names = [String]()
names.append(parts[0])

split が返す要素は String ではなく、Substring という別の型です。 String が必要な場所では String(parts[0]) のように包み直してください。

missing return in global function

テキスト
error: missing return in global function expected to return 'Int'
Swift
func add(_ a: Int, _ b: Int) -> Int {
    let c = a + b
}

戻り値の型を宣言した関数なのに、値を返さずに終わる経路があります。 return c のように、結果を return で返してください。

Fatal error: Index out of range(実行時)

テキスト
Fatal error: Index out of range
Swift
let a = [1, 2, 3]
print(a[3])

配列の範囲外を添字で読もうとしています。 要素数 3 の配列で使えるのは a[0] から a[2] までです。 ループの終了条件と、添字の最大値を見直してください。

Fatal error: Unexpectedly found nil(実行時)

テキスト
Fatal error: Unexpectedly found nil while unwrapping an Optional value
Swift
let a = Int(readLine()!)!
let b = Int(readLine()!)!

! を付けた場所に、中身のない値(nil)が来ました。 2 行読むコードに 1 行しか入力していないなど、読む回数と入力の行数のずれが典型です。

3 5 のような 1 行を丸ごと Int(...) に渡したときも、変換に失敗して同じエラーになります。 入力欄の内容と、問題の入力形式を見比べてください。