others - 在Swift,如何过滤数组中的对象

var campaigns: [Campaign] = []'nil' is incompatible with return type 'Campaign'


self.campaigns = self.campaigns.map({ (campaign) -> Campaign in


 if campaign.published == 1 {


 return campaign


 } else {


 return nil


 }


 })



时间: 原作者:

需要使用compactMap来删除nil响应,但你最好只使用filter


campaigns = campaigns.filter{$0.published == 1}



原作者:
...