Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
Swift HStack View no se ajusta al protocolo 'View'

He construido este código

 struct StarDifficultyView: View { var numberOfStarsToShow: Int var numberOfTotalStarsToShow: Int = 5 var body: some View { HStack{ var numberLeftToShow = numberOfStarsToShow ForEach(1..<numberOfTotalStarsToShow+1){_ in if(numberLeftToShow > 0){ Image(systemName: "star.fill") .foregroundColor(Color.yellow) numberLeftToShow -= 1 }else{ Image(systemName: "star.fille") .foregroundColor(Color.yellow) } } } }

}

Me da un error en la línea if(numberLeftToShow > 0){ diciendo "Escriba '()' no se puede ajustar a 'Ver'"

¿Alguien puede decirme qué estoy haciendo mal?

over 4 years ago · Santiago Trujillo
3 answers
Answer question

0

No importa, acabo de hacer esto

 struct StarDifficultyView: View { var numberOfStarsToShow: Int var numberOfTotalStarsToShow: Int = 5 var body: some View { HStack{ ForEach(1..<numberOfStarsToShow+1){_ in Image(systemName: "star.fill") .foregroundColor(Color.yellow) } ForEach(1..<numberOfTotalStarsToShow-numberOfStarsToShow+1){_ in Image(systemName: "star.fill") .foregroundColor(Color.gray) .opacity(0.7) } } } }

Básicamente, simplemente recorre la cantidad de estrellas amarillas para mostrar y luego calcula cuántas grises mostrar y hace otro ForEach para mostrar las sobrantes necesarias

over 4 years ago · Santiago Trujillo Report

0

¡No deseche el parámetro de cierre para ForEach !

 var body: some View { HStack{ ForEach(0..<numberOfTotalStarsToShow){ i in // don't ignore the "i" here by writing "_" // "i" will be different in each "iteration" // use that to figure out which image to show if(i < numberOfStarsToShow){ Image(systemName: "star.fill") .foregroundColor(Color.yellow) } else { Image(systemName: "star") .foregroundColor(Color.yellow) } } } }
over 4 years ago · Santiago Trujillo Report

0

Explicando el problema:

No debe agregar expresiones dentro del generador de vistas. Así que numberLeftToShow -= 1 arrojará un error porque devuelve un void (tipo 'aka'()) y esto no se ajusta a View ! ¡Esa es la razón exacta del compilador!

Nota 1

¡No use SwiftUI como el UIKit! Las vistas de SwiftUI pueden ejecutarse con el tiempo en cualquier cambio de estado y no deben usarse para calcular nada de esta manera

Nota 2

Puede convertir 1..<numberOfTotalStarsToShow+1 en un rango cerrado como 1...numberOfTotalStarsToShow (aunque no lo necesita en absoluto para esta pregunta)

Nota 3

Trate de no usar la rama y convierta su código if/else en algo como:

 Image(systemName: numberLeftToShow > 0 ? "star.fill" : "star.fille") .foregroundColor(Color.yellow)

Nota 4:

El límite inferior de un rango no puede ser menor que el rango superior, pero puede iterar sobre un rango invertido como:

 (1...numberOfTotalStarsToShow).reversed()

Nota 5:

¡Intente usar una única fuente de verdad como el propio parámetro forEach!

Nota 6:

Swift puede inferir el tipo y no es necesario que lo vuelvas a pasar: así que cambia Color.yellow a .yellow

Resultado final:

Aquí está la respuesta revisada del código (basada en la respuesta que usted mismo proporcionó):

 var body: some View { HStack { ForEach(1...numberOfTotalStarsToShow, id:\.self) { i in Image(systemName: "star.fill") .foregroundColor(i > numberOfStarsToShow ? .gray : .yellow) } } }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!