When I use switch statement in phase in asyncImage it gave me this error.
Trailing closure passed to parameter of type 'CGFloat' that does not accept a closure
I understand that docs uses if let statements to extract the image and get the error like here down.
My code:
AsyncImage(url: URL(string:stringURL)) { phase in
switch phase {
case .empty:
ProgressView()
case .success(let image):
image
.scaledToFit()
case .failure():
EmptyView()
}
}
As per Apple Docs:
AsyncImage(url: URL(string: "https://example.com/icon.png")) { phase in
if let image = phase.image {
image // Displays the loaded image.
} else if phase.error != nil {
Color.red // Indicates an error.
} else {
Color.blue // Acts as a placeholder.
}
My question is why I cannot use switch statement here. And what does this error means exactly?
Thanks.
CodePudding user response:
you can use a switch statement, use this, works for me:
case .failure(_): // <-- here
Here is the code I used to show that my answer works:
struct ContentView: View {
@State private var stringURL = "https://upload.wikimedia.org/wikipedia/commons/e/ef/Red-billed_gull,_Red_Zone,_Christchurch,_New_Zealand.jpg"
var body: some View {
AsyncImage(url: URL(string: stringURL)) { phase in
switch phase {
case .empty:
ProgressView()
case .success(let image):
image.resizable().scaledToFit()
case .failure(_): // <-- here
EmptyView()
@unknown default:
Image(systemName: "exclamationmark.icloud")
}
}
}
}