2017-10-04 1 views
1

이것은 현재 모델 클래스 코드입니다.Swift에서 이름을 알파벳순으로 정렬하려면 어떻게합니까?

final class ContactData 
{ 
    static let sharedInstance = ContactData() 

    private var contactList : [Contact] = 
      [Contact(name:"Mike Smith",email:"[email protected]"), 
      Contact(name:"John Doe",email:"[email protected]"), 
      Contact(name:"Jane Doe",email:"[email protected]")] 


    private init() 
    { 
     // SORTING HERE 
    } 

    var index = 0 

    func newContact(new:Contact) 
    { 
     contactList.append(new) 
     //sort 
    } 

    func updateContact(updated:Contact) 
    { 
     contactList[index]=updated 
     //sort 
    } 

    func previousContact() -> Contact 
    { 
     index-=1 
     if index < 0 
     { 
      index = contactList.count-1 
     } 
     return contactList[index] 
    } 

    func nextContact() -> Contact 
    { 
     index+=1 
     if index == contactList.count 
     { 
      index = 0 
     } 
     return contactList[index] 
    } 

    func firstContact() -> Contact 
    { 
     return contactList[0] 
    } 

    func currentContact() -> Contact 
    { 
     return contactList[index] 
    } 
} 

모든 것이 제대로 실행되고 있지만 사용 Contact의 배열을 알파벳순으로 시도했다 :

var sortedContacts = contactList.sorted{ 
      $0.localizedCaseinsensitiveCompare($1)==ComparisonResult.orderedAscending} 
     } 

을하지만 오류가 점점 오전 :

Value of type ' Contact ' has no member ' localizedCaseinsensitiveCompare '

여기에 질문을 통해 상대를 배열을 영문자 순으로 알 수있는 유일한 방법을 찾을 수있었습니다.

나는 당신이 소문자를 구별 Contact 사용자 정의 클래스의 경우를 비교할 수 없습니다 스위프트 3, 엑스 코드 8.3

답변

1

당신은 클래스 연락이 대등 프로토콜을 준수해야한다 : 당신은 그들의 name 특성을 비교해야

class Contact: Comparable, CustomStringConvertible { 
    let name: String 
    let email: String 
    init(name: String, email: String) { 
     self.name = name 
     self.email = email 
    } 
    var description: String { 
     return name + " - " + email 
    } 
    // provide your custom comparison 
    static func <(lhs: Contact, rhs: Contact) -> Bool { 
     return lhs.name.localizedCaseInsensitiveCompare(rhs.name) == .orderedAscending || 
       lhs.email.localizedCaseInsensitiveCompare(rhs.email) == .orderedAscending 
    } 
    // you will need also to make it conform to Equatable 
    static func ==(lhs: Contact, rhs: Contact) -> Bool { 
     return lhs.name == rhs.name && lhs.email == rhs.email 
    } 
} 

놀이터 테스트

let c1 = Contact(name:"Mike Smith",email:"[email protected]") 
let c2 = Contact(name:"John Doe",email:"[email protected]") 
let c3 = Contact(name:"John Doe",email:"[email protected]") 
let c4 = Contact(name:"Jane Doe",email:"[email protected]") 
let c5 = Contact(name:"Jane Doe",email:"[email protected]") 

let people = [c1, c2, c3, c4, c5] 
print(people) // "[Mike Smith - [email protected], John Doe - [email protected], John Doe - [email protected], Jane Doe - [email protected], Jane Doe - [email protected]]\n" 
print(people.sorted()) // "[Jane Doe - [email protected], Jane Doe - [email protected], John Doe - [email protected], John Doe - [email protected], Mike Smith - [email protected]]\n" 
+0

이 솔루션을 고려해야 할 몇 가지 사항이 있습니다. 모든 것은'name'에만 묶여 있습니다. 이것은 당신이 항상 이름으로 비교하고 이메일을 무시하기를 원한다고 가정합니다. 그것은 동일한 이름이지만 이메일이 다른 두 개의 다른 연락처를 동일하게 취급합니다. 그것은 미묘한 버그를 많이 일으킬 수 있습니다. 전자 우편이 비교되는 경우 이름이 동등한 것이 가장 좋습니다. – rmaddy

+0

내 의견은 OP에 자신의 맞춤 정렬을 제공합니다 –

+0

또는 설명 비교 –

0

을 실행하고 있습니다.

var sortedContacts = contactList.sorted { $0.name.localizedCaseInsensitiveCompare($1.name) == .orderedAscending} } 
+1

를 또는 연락처에 적합하게 비교 프로토콜 –

+0

@LeoDabus 네, 계획을 세우는 경우 더 나은 접근법입니다. 코드에서 많은 정렬을 사용하십시오. – the4kman

+0

@ the4kman 내 놀이터에서 이것을하면 내 기능이 기본적으로 비 효과가 아닌 오류를 던지고 있습니다. – Nonstoplive

관련 문제