ios - 如何从打印的结构中删除结构名称(swift4)

标签 ios swift struct printing

下面的代码打印结构数据。我只想打印结构数据而不显示结构名称。我怎样才能做到这一点?另请参阅下图。

   var contacts = [Person]()
override func viewDidLoad() {
    super.viewDidLoad()
}
    @IBAction func press(_ sender: Any) {
        contacts.append(Person(name: a.text!,  phone: Int(c.text!)!))
        print(self.contacts.description)

        label.text = self.contacts.description
    }

    struct Person {
        var name: String

        var phone: Int

    }}

enter image description here

最佳答案

有一个名为CustomStringConvertible的协议(protocol),应该用于打印结构。下面我演示了苹果在其文档中提供的简单代码。

    struct Point {
         let x: Int, y: Int
    }

    let p = Point(x: 21, y: 30)
    print(p)
    // Prints "Point(x: 21, y: 30)"

文档说:实现描述属性并声明 CustomStringConvertible 一致性后,Point 类型提供自己的自定义表示

     extension Point: CustomStringConvertible {
        var description: String {
        return "(\(x), \(y))"
        }
     }

     print(p)
     // Prints "(21, 30)"

Link is here

关于ios - 如何从打印的结构中删除结构名称(swift4),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46633926/

相关文章:

ios - 自定义TableView中的UIView背景颜色仅在滚动时改变,为什么?

ios - UIButton 中的 UIImage 用矢量图像像素化

swift - 如何在 Swift 中保留复杂的数据结构,关于前进方向的建议

c - 我如何释放一个结构?

swift - 将 Cookie 设置为来自 Swift NSURLSession 的 HTTP POST 请求

c# - 想知道一种在 C# 中使用 List<> 和结构来节省内存的方法

ios - 如何添加 Rate App 来解锁某些东西

ios - 在服务器数据库更新时通知 iOS 应用程序的最佳方式

ios - 缩放/动画UIView的一侧变小? -CGAffineTransformMakeScale

swift - Swift 中的标签原点位置