Reputation: 879
I have a Swift grammar question. I have a switch case in the function, and I need to make a nested switch case something like below.
func changeIcon(status: String){
switch status {
case "ready", "recording", "finished", "error":
if indicator.isAnimating {
indicator.stopAnimating()
indicator.hidesWhenStopped = true
}
indicator.isHidden = true
symbolImageView.isHidden = false
switch status{
case "ready":
symbolImageView.image = Images.streamIsReady
case "recording":
symbolImageView.image = Images.streamIsOngoing
case "finished":
symbolImageView.image = Images.close
case "error":
symbolImageView.image = Image.error
default:
print("default")
}
case "init":
symbolImageView.isHidden = true
indicator.isHidden = false
indicator.startAnimating()
default:
print("default")
}
}
I want to use a switch case (or if statement is also fine if it's possible) for checking if I display UIimage or UIActivityIndicator, and then use another switch case to determine which UIImage should I display. I was wondering if using a nested switch case is redundant and there is an alternative way to achieve the same thing.
Upvotes: 1
Views: 793
Reputation: 285039
You could add a function, for example
func changeIcon(status: String) {
switch status{
case "ready":
updateImage(.streamIsReady)
case "recording":
updateImage(.streamIsOngoing)
case "finished":
updateImage(.close)
case "error":
updateImage(.error)
case "init":
symbolImageView.isHidden = true
indicator.isHidden = false
indicator.startAnimating()
default:
print("default")
}
}
func updateImage(_ image : Images){
if indicator.isAnimating {
indicator.stopAnimating()
indicator.hidesWhenStopped = true
}
indicator.isHidden = true
symbolImageView.isHidden = false
symbolImageView.image = image
}
And I agree with Sulthan: Use an enum rather than a String
Upvotes: 2
Reputation: 130072
First of all, you should have an enum
:
enum Status: String {
// "init" renamed to "loading"
case loading, ready, recording, finished, error
var icon: UIImage? {
switch self {
case .loading:
return nil
case .ready:
return Images.streamIsReady
case .recording:
return Images.streamIsOngoing
case .finished:
return Images.close
case .error:
return Image.error
}
}
}
Then your code can become:
func changeIcon(status: Status) {
if status == .loading {
indicator.startAnimating()
} else {
indicator.stopAnimating()
}
let icon = status.icon
symbolImageView.isHidden = icon == nil
symbolImageView.image = icon
}
Statement indicator.hidesWhenStopped = true
should be part of your view setup and not inside this function.
Upvotes: 3