2017-10-10 91 views
2

我的代碼如下打印一個結構,我期望它的結果[]。我只是想要刪除它。我在下面的照片中圈出了文字。我覺得這與[Person]有關。如何從打印結構中刪除[]結構(swift4)

 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)" 
    }} 

enter image description here

回答

0

你打印的人組成的數組......不只是一個人。所以,你得到的方括號:

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 

我想你可以做這樣的事情:

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

這將加入了所有的接觸到一個單一的字符串,用換行分隔每個聯繫人。

此外,擺脫CustomStringConvertible中的初始換行符,因爲現在joined爲您提供分隔符。

+0

這可行,但我只能打印1行。 –

+0

好的,我已經爲你加入了聯繫人。讓我知道這是否適合你。 (然後檢查我的答案作爲您的解決方案!) –