2016-02-05 62 views
0

我有一個日期數組,其中包含當前加上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] 

我知道我所提供的代碼是錯誤的,我覺得我incorretly接近這一點。我應該怎麼做?

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)") 
          } 
         } 
        } 

回答

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%的安全。

+0

怎麼樣的合併運算符:'字典[$ 0 ] ?? 「」'。 BTW爲'zip'函數+1,我現在沒有那個。 – FranMowinckel

+0

謝謝,我沒有想到使用它。我相信它可以更短。在一行中創建字典會很好,但使用'reduce'創建數組或字典會降低性能。 – Eendje

+0

如果我想對UIImage數組做同樣的操作,該怎麼辦? – stackerleet

3

我在操場上試過這個。它的作用是迭代date array中的每個Int。然後它試圖在date array db中找到相同的Int。如果它能找到它,那麼它會嘗試在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("") 
    } 
} 
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 "" 
    } 
} 
+1

不錯!你的短版本是一個很好的接觸;)唯一的缺點是,它不是完全安全的。如果'datesDb'具有比'animalsDb'計數更多的匹配日期,則會崩潰。 – Eendje

相關問題