WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

SOLVED: return object in function

Forums > SwiftUI

struct Produtos : Identifiable, Codable{
    var id = UUID()
    var produto : String
    var descricao : String
    var imagem : [String]
    var preco : Double
    var destaque : Bool
    var categoria : String
    var ordenacao : Int
    var lojaID : Int
struct Loja : Identifiable, Codable {
    var id = UUID()
    var lojaId : Int
    var nome : String
    var logomarca : String
    var imagemcapa : String
    var telefone : String
    var frete : Double?
    var ordenacao : Int

I am in a loop of array of products, id I need to pass de Loja to a navigationlink. I try to do a function to search this.

    func buscaDadosLojaDoProduto (loja: [Loja], produtoLacoLojaId: Int) -> String {
        var nomeLoja = ""
        for x in loja where x.lojaId == produtoLacoLojaId {
            nomeLoja += x.nome
        return nomeLoja


    func buscaDadosLojanoProduto (loja: [Loja], produtoLacoLojaId: Int) -> Loja {
        var x = Loja(loja.self) ?
        for x in loja where x.lojaId == produtoLacoLojaId {
            x ?
        return Loja(x) ?

I want to pass entire loja that was inside the [Loja].....

Can you help me ?


Are you trying to return an array of Lojas where the id is produtoLacoLojaId, take a look at filter.


  func buscaDadosLojanoProduto (lojas: [Loja], produtoLacoLojaId: Int) -> [Loja]{
       return  lojas.filter { loga in
    return loga.lojaId == produtoLacoLojaId

Note that I am returning an array of Lojas here. If you want to return a loga, and you are sure they are unique, then return the first element of the filtered array, which will be an optional.

Here is how that works:

The filter will check the return value of all items in the array and if it is returns true in the closure it will add that item to the array being returned. ( i.e. the filtered array) I have used a fairly verbose version of that map method. The most compact way is here:

return  lojas.filter {$0.lojaId == produtoLacoLojaId}

in that case $0 is the element of the array ( a loja) and the return can be left out if there is one line.

Good time to look at filter and map and other such utilities. See here:




I just use [0] and its work fine!!! thanks!


Hacking with Swift is sponsored by Fernando Olivares

SPONSORED Fernando's book will guide you in fixing bugs in three real, open-source, downloadable apps from the App Store. Learn applied programming fundamentals by refactoring real code from published apps. Hacking with Swift readers get a $10 discount!

Read the book

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.