0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

株式会社D2C IDAdvent Calendar 2022

Day 3

[SwiftUI] @Stateを使ったViewで"'~View' initializer is inaccessible due to 'private' protection level"のエラーが発生する場合の対策

Last updated at Posted at 2022-12-02

概要

Gridを使った以下のようなViewを作成している際にPreviewで'ColorsView' initializer is inaccessible due to 'private' protection levelのエラーが発生した。

環境

Xcode 14.0.1

struct ColorsView: View {

    @State var colors: [Color]
    private var columns: [GridItem] = Array(repeating: GridItem(.flexible(), spacing: 16), count: 2)

    var body: some View {
        
        ScrollView(.vertical) {
            LazyVGrid(columns: columns, alignment: .center, spacing: 16) {
                ForEach($colors, id: \.self) { color in
                    color
                        .wrappedValue
                        .frame(height: 150)
                }
            }
            .padding()
        }
    }
}

struct ColorsView_Previews: PreviewProvider {
    
    @State static var colors: [Color] = [.red, .blue, .yellow, .green, .pink, .purple, .orange]
    
    static var previews: some View {
        ColorsView(colors: colors)
    }
}

スクリーンショット 2022-11-01 10.51.34.png

解決方法

@State変数、同じstructの変数がvarであるため発生していた模様。letに変えて解決.。

    private let columns: [GridItem] = Array(repeating: GridItem(.flexible(), spacing: 16), count: 2)

varであっても初期化されているのだから問題ないような...

別の方法

イニシャライザを使い初期化

    @State private var colors: [Color]
    private var columns: [GridItem] = Array(repeating: GridItem(.flexible(), spacing: 16), count: 2)

    init(colors: [Color]) {
        self.colors = colors
    }

イニシャライザを使う方法であれば@Stateの変数もprivateにでき、別の変数もvarのままで使える。
多分こっちが正解

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?