我正在尝试将通用Array方法compactMap包装在Array扩展中,以使该方法的目的更具意义/可读性.我只是试图获取一个Option of Optionals并从中删除任何和所有的nil值.
extension Array { public func removeNilElements() -> [Element] { let noNils = self.compactMap { $0 } return noNils // nil values still exist } }
我遇到的问题是这里的compactMap不起作用.零值仍然在结果数组noNils中.当我直接使用compactMap方法而不使用这个包装器时,我得到了没有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]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。