2017-10-10 1 views
0

내 구조가 지금 입력 된 순서대로 인쇄됩니다. 내가 뭘하고 싶습니다 문자열 부분을 알파벳 순서로 인쇄 얻을 수 있습니다.알파벳 순서로 레이블에 인쇄 된 정렬 구조

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

답변

1

당신은 Person 구조체의 name 속성을 주문 폐쇄와 sorted을 사용해야합니다.

let sortedContacts = contacts.sorted { $0.name < $1.name } 
+0

가 어떻게 알파벳 순서 등 주문 INT를 분야별로 내 구조체를 정렬 할 것입니다. a, 1; a : 4, : a, 6. {$ 0.name <$ 1.name && $ 1.phone> $ 0.phone} 시도했지만 그 작동하지 않습니다. –

0

당신은 다음과 같이 사용할 수 있습니다

(contacts.sorted {$0.description < $1.description}).map {$0.description}.joined(separator: "\n") 
관련 문제