KZY KZY - 7 months ago 21
Swift Question

How to convert this code from Objective-C to Swift?

[self.navigationItem.leftBarButtonItems enumerateObjectsUsingBlock:^(UIBarButtonItem* item, NSUInteger i, BOOL *stop) {
item.customView.alpha = alpha;
}];
[self.navigationItem.rightBarButtonItems enumerateObjectsUsingBlock:^(UIBarButtonItem* item, NSUInteger i, BOOL *stop) {
item.customView.alpha = alpha;
}];


How to convert this block of code to Swift ? thanks.

Answer

In Swift, leftBarButtonItems is an optional array [UIBarButtonItem]?, therefore it can be enumerated with optional chaining and forEach(). customView is also an optional UIView?, so assignment to the alpha property is done with optional chaining as well:

self.navigationItem.leftBarButtonItems?.forEach { item in
    item.customView?.alpha = alpha
}