简体   繁体   English

如何从打印结构中删除[](swift4)

[英]How to remove [] from print struct (swift4)

My Code below prints a struct its how I want it expect for the []. 我的下面的代码打印了一个结构,它对[]的期望值。 I just want it removed. 我只想将其删除。 I circled the text in the photo below. 我在下面的照片中圈出了文字。 I feel it has something to do with [Person]. 我觉得这与[人]有关。

      var contacts = [Person]()

@IBAction func press(_ sender: Any) {
    contacts.append(Person(name: a.text!,  phone: Int(c.text!)!))
    label.text = self.contacts.description
}}
struct Person {
var name: String
 var phone: Int}

extension Person: CustomStringConvertible {
var description: String {
return "\n\(name),\(phone)"
  }}

在此处输入图片说明

You're printing an array of Person ... not just a single person. 您正在打印一系列的人……而不仅仅是一个人。 So you get the square brackets: 这样就得到了方括号:

bash-3.2$ swift
Welcome to Apple Swift version 4.0 (swiftlang-900.0.63 clang-900.0.37). Type :help for assistance.
1> struct Person { var name: String; var phone: Int}
2> var contacts = [Person]()
contacts: [Person] = 0 values
3> contacts.append(Person(name: "john", phone: 911))
4> extension Person: CustomStringConvertible { public var description: String { return "\n\(name),\(phone)" }}
5> print(contacts)
[
john,911]
6> print(contacts[0])

john,911

I guess you could do something like this: 我猜你可以做这样的事情:

label.text = contacts.count == 0 ? "No people to contact" : contacts.map {$0.description}.joined(separator: "\n")

This will join up all the contacts into a single string with each contact separated by a newline. 这会将所有联系人合并为一个字符串,每个联系人之间用换行符分隔。

Also, get rid of that initial newline in the CustomStringConvertible because now the joined supplies the separator for you. 另外,摆脱掉CustomStringConvertible中的初始换行符,因为现在joined为您提供了分隔符。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM