2017-06-06 43 views
1

這是數組的我:循環數組 - 無法調用追加

var tblID = [String]() 
var tblUser = [String]() 
var tblEmployee = [String]() 

我試圖把它們添加到CSV文件,如:

let fileName = "Tasks.csv" 
    let path = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(fileName) 

    var csvText = "ID,USER,EMPLOYEE\n" 

    for content in [tblID, tblUser, tblEmployee] { 
     csvText.append(content) // Error here 
    } 

但在鏈接csvText.append(content)我收到錯誤消息:Cannot invoke 'append' with an argument list of type '([String])'

有什麼建議我可以在這裏做什麼?

+0

沒有平行數組 - 創建一個具有'id','user'&'employee'屬性的模型類型,然後有一個該類型的數組,然後遍歷它。 – Hamish

回答

0

您正嘗試使用append方法將單個字符串數組添加到單個字符串,但只需要一個字符串。

假設tblID,tblUser & tblEmployee總是包含相同數量的項目(否則將崩潰),你可以這樣做:

for content in [tblID, tblUser, tblEmployee] { 
    for loop in 0..<tblID.count { 
     csvText.append("\(tblID[loop]),\(tblUser[loop]),\(tblEmployee[loop]))\n") 
    } 
} 

這將添加一條線將增加由逗號的線分開ID ,用戶,員工,並在最後添加新行。

編輯:

爲了處理其中數組大小不匹配,你可以做到這一點的情況:

it tblID.count != tblUser.count || tblID.count != tblEmployee.count { 
    print ("error") 
} else { 
    // Do the above here 
} 

,你所能做的就是添加陣列或打印錯誤的內容最好的。你不能添加一些,然後打印錯誤,因爲如果tblID有5個條目,tblUser有4個,你不知道它是tblUser丟失還是最後的第一個條目。

+0

如何創建一個檢查以避免它崩潰,並返回一個'print(「error」)'而不是? –

+0

如果數組大小不匹配,編輯我的帖子以包括打印(「錯誤」)。 –

+0

謝謝!最後一個問題:如果每個表有價值,是否可以追加?假設我有'tblID'1,2和3.如果'tblUser'在ID 2中沒有值,它不會追加。如果你明白的話。 –

0

很難說沒有一個數據樣本,但我認爲這是你想要做什麼:

// might want to verify that all three arrays are the same size before doing this 
for i in 0..<tblID.length { 
    csvText.append("\(tblID[i]),\(tblUser[i]),\(tblEmployee[i])\n") 
} 

目前你只是想整個數組的字符串(這是不追加甚至允許),當我認爲你想訪問每個數組的內容時,一個接一個。