LoginSignup
12
10

More than 1 year has passed since last update.

SwiftUIでもprintデバッグしたい!!

Last updated at Posted at 2021-02-10

バッドノウハウです

通常SwiftUIではbodyの中にprintを書くことができません。

var body: some View {
    let width: CGFloat = 100 + 100
    print(width)               //エラー
    Rectangle()
        .frame(width: width)
}

この原因はprint(width)が実はVoidの値()を返していることです。そのため、ViewBuilderの側がVoidの値をViewとして解釈しようとして、エラーになります。

パッと思いつく解決策としては下のように、bodyの外で計算型プロパティを作って内部でprintを呼ぶ方法でしょうか。もちろんクロージャを即時実行する形でもいいと思います。

var width: CGFloat {
    let _width: CGFloat = 100 + 100
    print(_width)
    return _width
}

var body: some View {
    Rectangle()
        .frame(width: width)
}

あとはonAppear内部で

var body: some View {
   let width: CGFloat = {
        let _width: CGFloat = 100 + 100
        print(_width)
        return _width
    }()
    Rectangle()
        .frame(width: width)
}

何にせよちょっと面倒ですね。

そこで、let width = 100 + 100の方に着目します。これは文だから(値を返さないので)エラーになっていません。

そこでこうするとprintデバッグできるようになります。

var body: some View {
    let width: CGFloat = 100 + 100
    let _ = print(width)       //200
    Rectangle()
        .frame(width: width)
}

得られた値()を文の中で用いるので、何の問題もなく実行されます。コード量は1行も増えません。
これでSwiftUIでもスマートにprintデバッグできるようになりました!


SwiftUI3ではひっそりとデバッグ用関数が追加されたようです。以下の関数を使うとさらに幸せになれそうです。

let _ = print(Self._printChanges())
12
10
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
12
10