List comprehension in Swift

前端 未结 8 2245
伪装坚强ぢ
伪装坚强ぢ 2020-12-07 13:53

The language guide has revealed no trace of list comprehension. What\'s the neatest way of accomplishing this in Swift? I\'m looking for something similar t

8条回答
  •  我在风中等你
    2020-12-07 14:38

    Generally, a list comprehension in Python can be written in the form:

    [f(x) for x in xs if g(x)]
    

    Which is the same as

    map(f, filter(g, xs))
    

    Therefore, in Swift you can write it as

    listComprehension(xs: [X], f: X -> Y, g: X -> Bool) = map(filter(xs, g), f)
    

    For example:

    map(filter(0..<10, { $0 % 2 == 0 }), { $0 })
    

提交回复
热议问题