swift - 打印时如何将数组拆分为指定的行?

标签 swift xcode dictionary

我是软件开发新手,正在阅读 Big Nerd Ranch 的书“Swift Programming”。这本书设定的挑战之一是在包含 15 个邮政编码的字典中打印一个数组,并将它们分成三行,每行五个。格式必须完全匹配它在书中的显示方式。

在开发人员文档的帮助下,我尝试使用书中教授的信息来解决这个问题。

没有骰子。

这是我需要打印的内容:

Caterham has the following zip codes: [111, 111, 111, 111, 111,
                                       222, 222, 222, 222, 222,
                                       333, 333, 333, 333, 333]

然而这是我能得到的最接近的...

var areaCodes = ["Caterham": [111, 111, 111, 111, 111], "Coulsdon": [222, 222, 222, 222, 222], "Purley": [333, 333, 333, 333, 333]]

var caterhamCodes : [Int] = []

for (_, values) in areaCodes {
    caterhamCodes += values
}

print("Caterham has the following codes: \(caterhamCodes[0...4]),")
print("                                  \(caterhamCodes[5...9]),")
print("                                  \(caterhamCodes[10...14]).")

打印:

Caterham has the following postcodes: [111, 111, 111, 111, 111],
                                      [222, 222, 222, 222, 222],
                                      [333, 333, 333, 333, 333].

基本上,每次打印一个邮政编码 block 后,我都需要上面的内容减去一些方括号并且没有标点符号。这本书指定我可能需要使用一个称为终止符的参数。它还提到我可能需要学习如何在字符串文字中表示特殊字符。

我很欣赏这可能是一个简单答案的高层次问题,但我才开始学习几周,所以我希望能原谅我问了至少几个愚蠢的问题!

最佳答案

欢迎来到开发者社区,祝您玩得愉快! 我试图让答案尽可能简单,所以这是我的尝试:

var areaCodes = ["Caterham": [111, 111, 111, 111, 111],
                 "Coulsdon": [222, 222, 222, 222, 222],
                 "Purley": [333, 333, 333, 333, 333]]
let codesArray = areaCodes.values.sorted(by: { $0[0] < $1[0] })
let caterhamString = "Caterham has the following zip codes: ["
var printString = caterhamString

for (index, area) in codesArray.enumerated() {
   for code in area {
      printString += "\(code), "
   }

   if index != codesArray.count - 1 {
      printString += "\n" + String(repeating: " ", count: caterhamString.count)
   }
}

print(printString.dropLast(2).appending("]"))

希望对您有所帮助!祝你好运!

关于swift - 打印时如何将数组拆分为指定的行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55811991/

相关文章:

ios - 使 `UIView` 线在自身中心变成半圆

ios - 奇怪的 NavBar 在 ios 11 Xcode 9 中拉伸(stretch)

python - 从字典列表中删除重复的字典

dictionary - map 与 mapM 行为

swift - FireStore swift : Accessing counts and document details for use in a table

ios - 访问另一个类中的 socket (Swift)

Xcode 如何为打开图像添加 IBAction?

ios - XCode 未构建我的项目

c++ - 选择容器以插入多个数据库记录

ios - 带铸件的开关