I'm trying to get a particular UIImage in one of my subviews, but am getting the following error Value of type 'UIView' has no member 'image' with
for subview in self.view.subviews.filter{$0 is UIImageView} {
print(subview.image)
}
I understand how self.view.subviews are of the type UIView
But what am I supposed to do?
CodePudding user response:
You can use a case pattern (like in switch statements) in a for loop. This has the slight advantage of not creating an intermediate array.
See also: https://alisoftware.github.io/swift/pattern-matching/2016/05/16/pattern-matching-4/
for case let subview as UIImageView in self.view.subviews {
print(subview.image)
}
CodePudding user response:
You're filtering the subviews array, but you still need to cast them to a UIImageView — for example:
for subview in self.view.subviews.filter{ $0 is UIImageView } {
if let imageView = subview as? UIImageView {
print(imageView.image)
}
}
However, this is a bit repetitive. You probably want compactMap(_:) instead.
for imageView in self.view.subviews.compactMap { $0 as? UIImageView } {
print(imageView.image)
}
