2

I want to animate all views (based on tag) with an alpha change, but I am getting a "cannot assign alpha to view" error. What would be a good way to do this?

All the views have an alpha of 0 upon being added as a subview of myCustomView

func transitionEffects() {
    UIView.animateWithDuration(0.5, animations: {
        for view in self.myCustomView.subviews {
            if(view.tag != 999) {
                view.alpha = 1
            }
        }
    })
}
haitham
  • 3,398
  • 6
  • 21
  • 35

1 Answers1

4

This is because Swift needs to know the kind of objects inside the subviews NSArray before sending methods.
NSArray is automatically converted in a swift Array of AnyType objects, thus it doesn't know which kind of objects are extracted from the array. By casting the array to be an array of UIViews objects everything should work fine.

func transitionEffects() {
    UIView.animate(withDuration: 0.5, animations: {
        for view in self.myCustomView.subviews as [UIView] {
            if (view.tag != 999) {
                view.alpha = 1
            }
        }
    })
}
Karen Hovhannisyan
  • 1,140
  • 2
  • 21
  • 31
Andrea
  • 26,120
  • 10
  • 85
  • 131
  • I would expect the Swift compiler to complain unless you wrote `view.alpha = 1.0`. Swift doesn't automatically "promote" scalars from int to float to double like C/Objective-C does. Curious that it doesn't. – Duncan C Jul 08 '15 at 20:13
  • That makes sense Duncan, but as far as I remember when I copied this code in an app of mine it didn't. Mumble.. But yours is good point. – Andrea Jul 08 '15 at 20:15
  • 1
    @DuncanC that's because `CGFloat` is `IntegerLiteralConvertible`. – rintaro Jul 10 '15 at 12:24