LoginSignup
3
1

More than 1 year has passed since last update.

【Swift】【エラー】Binary operator '<' cannot be applied to two 'Int?' operands

Last updated at Posted at 2021-12-14

どういうことか

たとえばこんなコードを書いたときに発生する。

let a: Int? = 1
let b: Int? = 2

print(a < b)

整数型?である2つの被演算子(オペランド)に対して二項演算子(Binary operator)は使うことができない」と言っている。
ここのキモは ? が付いたオプショナル型を比較しようとしていることで、どうもオプショナル型の比較はできないっぽい。

アンラップする

let a: Int? = 1
let b: Int? = 2

print(a! < b!)

// true

これでもいけるけどなるべく強制アンラップは使いたくない。
if let で優しくアンラップする。

let a: Int? = 1
let b: Int? = 2

if let first = a, let second = b {
    print(first < second)
}

// true

おわり(´・ω・`)

3
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
3
1