Value of type 'UIView' has no member 'image'

Viewed 325

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?

2 Answers

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)
}
Related