如何将此代码从Objective-C转换为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; 
    }]; 

如何将这段代码转换为Swift?谢谢。如何将此代码从Objective-C转换为Swift?

+0

您可以使用循环 – Bhupesh

+0

现在很难选择哪个回答接受,downvoted假设笔者没”不要试图解决问题:/ – Injectios

+0

至少应该尝试学习迅捷的语言。 –

在Swift中,leftBarButtonItems是一个可选阵列[UIBarButtonItem]?, 因此可以使用可选的链接和forEach()进行枚举。 customView也是一个可选UIView?,所以分配到alpha 属性与可选的链接要做的事:

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

有很多很酷的obj-c来快速的网站。使用其中一个并整理结果,你就可以开始了!

这是objectivec2swift.com结果:

self.navigationItem.leftBarButtonItems.enumerateObjectsUsingBlock({(item: UIBarButtonItem, i: Int, stop: Bool) -> Void in 
    item.customView.alpha = alpha 
}) 
self.navigationItem.rightBarButtonItems.enumerateObjectsUsingBlock({(item: UIBarButtonItem, i: Int, stop: Bool) -> Void in 
    item.customView.alpha = alpha 
}) 

但是,这还不是最SWIFTY代码。让我们来整理它:

self.navigationItem.leftBarButtonItems?.forEach { 
    $0.customView?.alpha = alpha 
} 
self.navigationItem.rightBarButtonItems?.forEach { 
    $0.customView?.alpha = alpha 
} 

看看那!太狡猾了!

+1

除非我错了,否则这个(以及以前答案中的代码)不能编译。 –

+0

是的,我第一次没有测试代码。 @MartinR – Sweeper