大佬教程收集整理的这篇文章主要介绍了swift – 在类扩展中包装泛型方法,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
extension Array { public func removeNilElements() -> [Element] { let noNils = self.compactMap { $0 } return noNils // nil values still exist } }
我遇到的问题是这里的compactMap不起作用.零值仍然在结果数组noNils中.当我直接使用COR_876_11845@pactMap方法而不使用这个包装器时,我得到了没有nil值的数组所需的结果.
let buttons = [actionMenuButton,createButton] // [UIBarButtonItem?] let nonNilButtons = buttons.compactMap { $0 } // works correctly let nonNilButtons2 = buttons.removeNilElements() // not working
我没有正确设计我的扩展方法吗?
extension Array { public func removeNilElements<T>() -> [T] where Element == T? { let noNils = self.compactMap { $0 } return noNils } }
let a = [1,2,nil,3,4] // The type of a is [Int?] let b = a.removeNilElements() // The type of b is [Int] print(b) // [1,4]
以上是大佬教程为你收集整理的swift – 在类扩展中包装泛型方法全部内容,希望文章能够帮你解决swift – 在类扩展中包装泛型方法所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。