如何将元组数组转换为字符串?

时间:2019-01-27 09:22:29

标签: arrays swift string

我正在从文件中读取以下数据:

-LX-A7q4_8kFE4I_-iip,1
-LWyCOhwO_lUwMt-dOOa,1
-LWwVCZL5sfQYd4WtSHw,1

每行用“ \ n”分隔,每个元素用逗号分隔。

我能够读取文件,并将内容放入具有正确行和列的数组中。

然后,我可以过滤数组以删除所需的行。最后,我想以相同的格式将数组写回到文件中。我的代码如下:

// This filters the array and gets me the rows I want.  
func writeToFile() {          
    let filteredMessageID = result.filter { $0.messageID != nominationKeyForReadStatus }
    //This is my attempt at converting the array to a string, before I try writing the string back to the file.  
    let filteredMessageIDJoinedString = filteredMessageID.joined(separator:"\n")
}

这最后一段代码显然是错误的,作为我的数组,过滤后以filteredMessageID返回的结果如下:

// ▿ 2 elements
  ▿ 0 : 2 elements
    - messageID : "-LWyCOhwO_lUwMt-dOOa"
    - readStatus : "1"
  ▿ 1 : 2 elements
    - messageID : "-LWwVCZL5sfQYd4WtSHw"
    - readStatus : "1"

如何将filteredMessageID转换回看起来像这样的字符串?

"-LWyCOhwO_lUwMt-dOOa,1\n-LWwVCZL5sfQYd4WtSHw,1"

谢谢!

1 个答案:

答案 0 :(得分:1)

map之前需要joined才能将每个元组转换为String

let filteredMessageIDJoinedString = filteredMessageID
    .map{ "\($0.messageID),\($0.readStatus)" } // notice the comma in the middle
    .joined(separator:"\n")

您的格式看起来像CSV。您可以了解如何使用Swift here读写CSV。