Swifters:
        I’m dealing with a JSON API where sets of options are returned as 
arrays of strings. Representing these as OptionSets seems ideal. I can decode 
the arrays of strings into an array of individual OptionSet values, but I’ve 
run into a dead end when trying generically reduce the array of OptionSets to a 
single OptionSet value. I’ve tried variety of ways of definition a Collection 
extension, even tried defining a global function, but I can’t seem to use the 
OptionSet sequence initializer or reduce itself (cannot invoke insert with 
argument of type (OptionSet) (or T)). Any guidance here? 
        Here’s what I’ve tried:

extension Collection where Iterator.Element == OptionSet {
    
    func reduced() -> Iterator.Element {
        return reduce(Iterator.Element()) {
            var newResult = $0
            newResult.insert($1)
            return newResult
        }
    }
    
}

extension Collection where Iterator.Element == OptionSet {
    
    func reduced<T: OptionSet>() -> T {
        return reduce(T()) {
            var newResult = $0
            newResult.insert($1)
            return newResult
        }
    }
    
}


extension Collection where Iterator.Element == OptionSet {
    func reduced() -> Iterator.Element {
        return Iterator.Element(self)
    }
}

func reduced<T: OptionSet>(_ options: [T]) -> T {
    return options.reduce(T()) {
        var newResult = $0
        newResult.insert($1)
        
        return newResult
    }
}

Jon Shier
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to