Swift Conditional Conformance with Any

后端 未结 2 1135
小鲜肉
小鲜肉 2021-01-27 05:03

Let\'s assume an array of Result. We want the array to be reduced to a Result of an array. For example:

let z: [Result         


        
2条回答
  •  无人共我
    2021-01-27 05:34

    You can move constraints to the function to make it generic:

    extension Array {
        func reduced() -> Result<[T], Error> where Element == Result {
            return self.reduce(.success([T]())) { accumulator, result in
                ...
            }
        }
    }
    

    Note: A variable of type Int will not match Any as it's a different type. Variables of type Any need to be casted down to Int.

提交回复
热议问题