打印时如何将阵列分成指定的行?

时间:2019-04-23 13:08:13

标签: swift xcode dictionary

软件开发的新手,我正在研究Big Nerd Ranch的书“ Swift Programming”。本书所面临的挑战之一是在包含15个邮政编码的字典中打印一个数组,并将其分成3行,每组5条。格式必须完全匹配。

在开发人员文档的帮助下,我尝试使用本书中介绍的信息解决问题。

没有骰子。

这是我需要打印的:

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].

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

我很欣赏这可能是一个简单的答案的高水平问题,但是我还需要学习几个星期,所以希望我能提出至少一些愚蠢的问题而得到原谅!

2 个答案:

答案 0 :(得分:1)

欢迎来到开发者社区,祝您生活愉快! 我正在尝试尽可能简单地回答,所以这是我的尝试:

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("]"))

希望这会有所帮助!祝你好运!

答案 1 :(得分:0)

这是获取所需输出的一种方法:

let intro = "Caterham has the following zip codes: ["
let spaces = ",\n" + String(repeating: " ", count: intro.count)

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

let codes = areaCodes.values.sorted { $0[0] < $1[0] }

var output = intro +
    codes.map { $0.map{ String($0) }.joined(separator: ", ") }
    .joined(separator: spaces)
    + "]"

print(output)

哪些印刷品

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