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?
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
¡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) } } } } 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!
¡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
Puede convertir 1..<numberOfTotalStarsToShow+1 en un rango cerrado como 1...numberOfTotalStarsToShow (aunque no lo necesita en absoluto para esta pregunta)
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)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()¡Intente usar una única fuente de verdad como el propio parámetro forEach!
Swift puede inferir el tipo y no es necesario que lo vuelvas a pasar: así que cambia Color.yellow a .yellow
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) } } }