skip to Main Content

I have this model:

struct MemeModel: Codable {
    var id: Int
    var title: String
    var nickname: String
}

And try to pass an initialized custom Array from preview to view:

struct Comments_Previews: PreviewProvider {
    static var previews: some View {
        Comments(memes: arrayOf(MemeModel(123, "blaaa", "joooo"),MemeModel(456, "hhhhh", "dddd")),memeid: 777)
    }
}

I get: Cannot find 'arrayOf' in scope

This is in the Comments view:

@Binding var memes: [MemeModel]
@Binding var memeid: Int

3

Answers


  1. As Joakim pointed out in his comment, there is no arrayOf in swift. Probably you remember this from Kotlin.

    You should construct your MemeModel array as follows:

    [MemeModel(id: 123, title: "blaaa", nickname: "joooo"), MemeModel(id: 456, title: "hhhhh", nickname: "dddd")]
    
    Login or Signup to reply.
  2. Init it as @State property

        struct Comments_Previews: PreviewProvider {
            @State var memes = [MemeModel(id: 123, title: "blaaa", nickname: "joooo"), MemeModel(id: 456, title: "hhhhh", nickname: "dddd"), MemeModel(id: 789, title: "hhhhh", nickname: "dddd")]
    Comments(memes: $memes)
    
    Login or Signup to reply.
  3. In Swift you can just use [element, element, element] to create a literal array. Your view needs a @Binding, so you can’t just pass the array. You need to convert it to a bound value. You can use Binding.constant, abbreviated to .constant to create a constant binding.

    struct Comments_Previews: PreviewProvider {
        static var previews: some View {
            Comments(memes: .constant([MemeModel(123, "blaaa", "joooo"),MemeModel(456, "hhhhh", "dddd")]),memeid: 777)
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search