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      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.