UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Simple Data in Swift UI -> Error

Forums > SwiftUI

Cannot convert value of type '[Usuario]' to expected argument type 'Usuario'

//
//  CompuseView.swift
//  Testes
//
//  Created by Guilherme on 25/05/21.
//

import SwiftUI

struct Usuario: Identifiable, Codable {
    var id = UUID()
    var nome : String
    var sobrenome : String
}

struct userRowView: View {
    var usuario : Usuario
    var body: some View {
        HStack {
            Text(usuario.nome)
            Text(usuario.sobrenome)
        }
    }
}

struct CompuseView: View {
    let usuario = [
        Usuario(nome: "Guilherme", sobrenome: "Tell"),
        Usuario(nome: "Marina", sobrenome: "Dualipa")
    ]
    var body: some View {

        ForEach(usuario) { row in
            userRowView(usuario: usuario)
        }

    }
}

struct CompuseView_Previews: PreviewProvider {
    static var previews: some View {
        CompuseView()
    }
}

How can i solve this error, is a problem with my array data ?

3      

Hey,

Inside your For Loop you should be passing "row" to userRowView and not "usuario". Like this:

struct CompuseView: View {
    let usuario = [
        Usuario(nome: "Guilherme", sobrenome: "Tell"),
        Usuario(nome: "Marina", sobrenome: "Dualipa")
    ]
    var body: some View {

        ForEach(usuario) { row in
            userRowView(usuario: row)
        }

    }
}

The error message is telling you that you are supposed to pass one Usuario but you are passing an array of Usuario, as indicated by the [Usuario]. Each usuario in your usuario array is called "row" when you are inside the For Loop. Maybe it would have been easier to read if you called your array of users -> usuarios and each user -> usuario. Like this:

struct CompuseView: View {
    //CHANGE HERE
    let usuarios = [
        Usuario(nome: "Guilherme", sobrenome: "Tell"),
        Usuario(nome: "Marina", sobrenome: "Dualipa")
    ]
    var body: some View {

        // ANOTHER CHANGE
        ForEach(usuarios) { usuario in
            userRowView(usuario: usuario)
        }

    }
}

Espero ter ajudado :D

3      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.