List comprehension in Swift

前端 未结 8 2247
伪装坚强ぢ
伪装坚强ぢ 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:41

    As of Swift 2 you can do something like this:

    var evens = [Int]()
    for x in 1..<10 where x % 2 == 0 {
        evens.append(x)
    }
    
    // or directly filtering Range due to default implementations in protocols (now a method)
    let evens = (0..<10).filter{ $0 % 2 == 0 }
    

提交回复
热议问题