【问题标题】:Swift arrays of stringsSwift 字符串数组
【发布时间】:2017-01-08 15:22:24
【问题描述】:

我有一个字符串数组。

    var animals = ["cats 99", "dogs 42", "chimps 45", "moose 98"]
    var excludeAnimalArray = ["chimps", "dogs"]

输出应该是“cats 99”、“moose 98”。请记住,无法判断动物旁边的数字是多少。

【问题讨论】:

  • 结果是否应该按数值排序?还是只是巧合?

标签: arrays swift filter


【解决方案1】:

更短的filter

let result = animals.filter { animal in
    !excludeAnimalArray.contains { animal.hasPrefix($0) }
}

【讨论】:

  • 好了!不错:)
  • 您可以在代码前添加let set = Set(excludeAnimalArray),然后使用set 代替excludeAnimalArray。这将使执行速度更快。
  • 已解决...清新干净。
【解决方案2】:

这里有一个快速的答案,虽然我敢肯定也有一种不那么必要/更纯粹的功能方式。

var animals = ["cats 99", "dogs 42", "chimps 45", "moose 98"]
var excludeAnimalArray = ["chimps", "dogs"]

var result = animals.filter{
    animal in
    var include = true
    excludeAnimalArray.forEach{ if animal.hasPrefix($0){ include=false } }
    return include
}

print(result) //["cats 99", "moose 98"]

【讨论】:

    【解决方案3】:
    animals.sort = {
        // return sort logic here
    }
    

    您可以查看示例here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-20
      • 2015-09-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多