My struct is printed in the order of time added right now. What I would like to do is get the string part printed in alphabetical order.
import UIKit
class ViewController: UIViewController {
@IBOutlet var c: UITextField!
@IBOutlet var a: UITextField!
@IBOutlet var label: UILabel!
var contacts = [Person]()
@IBAction func press(_ sender: Any) {
contacts.append(Person(name: a.text!, phone: Int(c.text!)!))
label.text = contacts.count == 0 ? "No people to contact" : contacts.map { $0.description }.joined(separator: "\n")
}
}
struct Person {
var name: String
var phone: Int
}
extension Person: CustomStringConvertible {
var description: String {
return "\(name),\(phone)"
}
}
您应该使用带闭包的sorted
,该闭包对Person
结构体的name
属性进行sorted
。
let sortedContacts = contacts.sorted { $0.name < $1.name }
您可以这样使用:
(contacts.sorted {$0.description < $1.description}).map {$0.description}.joined(separator: "\n")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.