LoginSignup
2

More than 5 years have passed since last update.

String interpolation produces a debug description for an optional value; did you mean to make this explicit?

Last updated at Posted at 2018-11-27

過去に出会った警告メッセージとその対処方法備忘録

環境

  • XCode
  • Swift4.2

警告メッセージ

String interpolation produces a debug description for an optional value; did you mean to make this explicit?

警告発生コード

var text:String? = nil
text = "hoge"

print("\(text)")//warning

原因と対処方法

原因

Optional型でwrapされている文字列を、wrapしたまま直接print出力しようとしたことが原因みたい

対処方法

この場合は、unwrapしてから出力してあげることで解決した。

対処済みコード1

強制unwrap

var text:String? = nil
text = "hoge"

print("\(text!)")

対処済みコード2

冗長的だけど、明示的にunwrap

var text:String? = nil
text = "hoge"

if let text = text
{
    print("\(text)")
}
else
{
    print("nil")
}       

対処済みコード3

??演算子を利用してtextがnilの時のデフォルト値を指定しても良い

var text:String? = nil
text = "hoge"
print("\(text ?? "text is nil")")

対処済みコード4

Optionalそのままでいいから、警告を消したい時は以下のように記述する

var text:String? = nil
text = "hoge"
print("\(text as String?)")

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