如何使用filter方法代替in循环?迅速

时间:2017-12-01 01:15:40

标签: arrays swift

我想将BookingFeedback数组的每个元素的bookings属性分配给arrayOfFeedBackValues。是否有比在循环中更短的版本?

     //long version
  let bookings = [FireBaseData]()
  var arrayOfFeedBackValues = [Double]()
       for item in bookings{
          if item.BookingFeedback != nil {
            arrayOfFeedBackValues.append(Double(item.BookingFeedback)!)
           }
       }

//attempted short version. How can I make the returned value be of type Double?
  var arrayOfFeedBackValues = bookings.filter {$0.BookingFeedback != nil}

2 个答案:

答案 0 :(得分:0)

您可以使用map

arrayOfFeedBackValuesa.append(contentsOf: 
                               bookings.filter {$0.BookingFeedback != nil}
                                       .map { Double($0.BookingFeedback)! })

答案 1 :(得分:0)

你可以尝试这个我认为

var arrayOfFeedBackValues: [Double] = bookings.flatMap { $0.BookingFeedback == nil ? nil : Double($0.BookingFeedback!) }