【问题标题】:how to get array entry to print on new line each time (swift3)如何让数组条目每次在新行上打印(swift3)
【发布时间】:2017-10-05 05:49:57
【问题描述】:

当我的数组被打印时,条目被打印在同一行。我已经以几种方式尝试了 \n 命令,但我还没有让它工作。我只想在 1 行上打印 1 个数组条目,然后移至下一行。 pic of array printed out

var arrayOfInt = [Int]()


 let cars = arrayOfInt.map { "car \($0)" }
  label.text =  String(describing: cars)

【问题讨论】:

    标签: arrays swift printing return line


    【解决方案1】:

    试试这个

    arrayOfInt.forEach{print($0)}
    

    【讨论】:

      【解决方案2】:

      列出数组元素及其各自索引的扩展。

      extension Array
      {
          /// Prints self to std output, with one element per line, prefixed by
          /// the element's index in square brackets.
      
          public func printByIndex(delimiter: String = " ")
          {
              for (index, value) in self.enumerated()
              {
                  print("[\(index)]\(delimiter)\(value)")
              }
          }
      }
      

      用法:

      ["Foo", "Bar", "Baz"].printByIndex()
      
      // [0] Foo
      // [1] Bar
      // [2] Baz
      
      
      ["Foo", "Bar", "Baz"].printByIndex(delimiter: " = ")
      
      // [0] = Foo
      // [1] = Bar
      // [2] = Baz
      

      【讨论】:

        【解决方案3】:

        阿兰的回答很甜蜜。太感谢了。我到处都用过,哈哈。

        我正在添加另一个带有 JSON 数组对象的版本并使用 JSONDecoder 进行解码。您可能有 100 个对象,很难在控制台中分别读取每个对象。

        calendarObject = try JSONDecoder().decode(Array< CalendarObject >.self, from: data)
        let objs = calendarObject.map { "objs \($0)" }.joined(separator:"\n")
        print(objs)
        
        // objs calendarObject(event: "aaa", where: "xmarksthespot", from: "1:00", to: "2:00")
        // objs calendarObject(event: "bbb", where: "ymarksthespot", from: "2:00", to: "3:00")
        // objs calendarObject(event: "ccc", where: "zmarksthespot", from: "3:00", to: "4:00")
        

        【讨论】:

          【解决方案4】:

          你试过了吗?

          label.text = arrayOfInt.map { "car \($0)" }.joined(separator:"\n")
          

          【讨论】:

          • 太棒了。在我的项目中使用它:) 我使用 JSONDecoder 添加了一个示例版本。
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-06-16
          • 1970-01-01
          相关资源
          最近更新 更多