I found the very clever ideas here, and could make it work…
https://stackoverflow.com/questions/25064644/how-to-determine-if-a-generic-is-an-optional-in-swift
https://stackoverflow.com/questions/28190631/creating-an-extension-to-filter-nils-from-an-array-in-swift/38548106#38548106
protocol OptionalType {
associatedtype Wrapped
func map<U>(_ f: (Wrapped) throws -> U) rethrows -> U?
}
extension Optional: OptionalType {}
extension Sequence where Iterator.Element: OptionalType {
private func removeNils() -> [Iterator.Element.Wrapped] {
var result: [Iterator.Element.Wrapped] = []
for element in self {
if let element = element.map({ $0 }) {
result.append(element)
}
}
return result
}
var total : Int {
self.removeNils().count
}
}
let ar : [Int?] = [1, 2, nil, 4]
print(ar.total)
Or specifically the Array extension:
protocol OptionalType {
associatedtype Wrapped
func map<U>(_ f: (Wrapped) throws -> U) rethrows -> U?
}
extension Optional: OptionalType {}
extension Array where Element: OptionalType {
private func removeNils() -> [Element.Wrapped] {
var result: [Element.Wrapped] = []
for element in self {
if let element = element.map({ $0 }) {
result.append(element)
}
}
return result
}
var total : Int {
self.removeNils().count
}
}
let ar : [Int?] = [1, 2, nil, 4]
print(ar.total)