如何用其他值替换更改的数组?

时间:2016-02-05 15:49:57

标签: ios arrays swift

我有一个包含当天加10天的日期数组,我从数据库导入一个数组。我也有一个动物名字阵列。根据导入的内容,我想将动物名称放在过滤后的数组中。例如:

  date array: `[9, 10, 11, 12, 13, 14, 15, 16, 17, 18]`
  imported date array from db: [9, 12, 14, 18]
  imported animal name array from db: [dog, cat, tiger, sheep]

这就是我希望过滤的动物名称看起来像

filtered animal name array: [dog, "", "", cat, "", tiger, "", "", "", sheep]

我知道我提供的代码是错误的,我觉得我正在接近这个问题。我该怎么做?

 for(var j = 0; j < self.arrayofweek.count; j++){
                        for(var t = 0; t < self.datesfromdb.count; t++){
                            if(self.date[t] == self.datearray[j]){
                                self.namefiltered[t] = self.tutorname[j]
                                 print("filtered name \(self.namefiltered)")
                            }
                        }
                    }

3 个答案:

答案 0 :(得分:4)

数据:

let dates = [9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
let imported = [9, 12, 14, 18]
let animals = ["dog", "cat", "tiger", "sheep"]

返工:

let filtered = dates.map { zip(imported, animals).map { $0.0 }.indexOf($0).map { animals[$0] } ?? "" }

输出:

print(array) // ["dog", "", "", "cat", "", "tiger", "", "", "", "sheep"]

基于FranMowinckel的回答,但100%安全。

答案 1 :(得分:3)

我在操场上试过这个。它的作用是迭代Int中的每个date array。然后,它会尝试在Int中找到相同的date array db。如果它可以找到它,那么它会尝试在animal array中获取索引和查找。我更新了一些变量名称,因此您需要翻译它们。

let date = [9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
let foundDates = [9, 12, 14, 18]
let animals = ["dog", "cat", "tiger", "sheep"]

var filteredAnimals = [String]()
for currentDate in date {
    // Look up the date  in the foundDates array
    // If it's found, ensure that index is in bounds of the animal array
    if let index = foundDates.indexOf(currentDate) where (0..<animals.count).contains(index) {
        filteredAnimals.append(animals[index])
    } else {
        filteredAnimals.append("")
    }
}

答案 2 :(得分:1)

编辑,甚至更短:

dates.map { datesDb.indexOf($0).map { animalsDb[$0] } ?? "" }

只需使用地图功能(这不会创建任何辅助数组或字典):

var dates = [9, 10, 11, 12, 13, 14, 15, 16, 17, 18]
var datesDb = [9, 12, 14, 18]
var animalsDb = ["dog", "cat", "tiger", "sheep"]

let result = dates.map { date -> String in
  if let index = datesDb.indexOf(date) where index < animalsDb.count {
    return animalsDb[index]
  } else {
    return ""
  }
}
相关问题