繁体   English   中英

在Swift3中排序

[英]Sorting in Swift3

我正在从模型(即Contacts获取数据。 然后,我根据name属性对此模型进行排序。 但是结果不是以排序的方式得出的。 我正在使用以下代码对数据进行排序:

 func filterArrayAlphabatically(contacts : [Contact])
    {

        let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters.map({ String($0)})

        let all_Contacts =  contacts.sorted { $0.name < $1.name } //Sort model data as per name

        var result = [String:[Contact]]()

        for letter in alphabet
        {
            result[letter] = []

            for cntct in all_Contacts
            {
                let ctc : Contact! = cntct 
                let name : String! = ctc.name.capitalized

                if name.hasPrefix(letter)
                {
                  result[letter]?.append(cntct)
                }
            }
        }

        print("result......\(result)")
    }

它给我的输出如下:

result......["M": [], "K": [<App.Contact: 0x7c6703e0>], "E": [], "U": [], "Y": [], "H": [<App.Contact: 0x7c6701a0>], "X": [], "A": [<App.Contact: 0x7c670120>, <App.Contact: 0x7c670440>], "D": [<App.Contact: 0x7c6700b0>, <App.Contact: 0x7c670160>], "I": [], "R": [], "G": [], "P": [], "O": [], "L": [], "W": [], "C": [], "V": [], "J": [<App.Contact: 0x7c66f990>], "Q": [], "T": [], "B": [], "N": [], "Z": [], "S": [], "F": []]

我想以类似的方式输出:

 result......["A": [], "B": [<App.Contact: 0x7c6703e0>], "C": [], "D": []]

我做错了什么? 或是否有其他排序方式。 谢谢!

编辑:我尝试以下代码以使正确的顺序:

let sortedArray = result.sorted
    {
        (struc1, struc2) -> Bool in
        return struc1.key < struc2.key
    }

好的,这给了我想要的正确顺序结果。 但是问题是我想使用它,但是我不知道。 由于我有var arr_Contacts = [String:[Contact]]() 我想将sortedArray分配给arr_Contacts 我怎样才能做到这一点?

当我分配它给警告是:

在此处输入图片说明

它给出了错误:

在此处输入图片说明

尝试使用这种格式进行排序。

class Contact {
    var name: String = ""
    var lastName: String = ""

    public init (name: String, lastName: String ){
        self.name = name
        self.lastName = lastName
   }
}

let contact1 = Contact(name: "V", lastName: "W")
let contact2 = Contact(name: "G", lastName: "W")
let contact3 = Contact(name: "A", lastName: "C")
let contact4 = Contact(name: "P", lastName: "W")
let contact5 = Contact(name: "F", lastName: "W")
let contact6 = Contact(name: "A", lastName: "W")
let contact7 = Contact(name: "A", lastName: "W")
var contacts: [Contact]

contacts = [contact1, contact2, contact3, contact4, contact5, contact6, contact7]

let sortedContact = contacts.sorted{(struct1, struct2) -> Bool in
    return struct1.name < struct2.name
}
//At this point our contact are sorted, now add to dictionnary

var arr_Contacts = [String:[Contact]]()
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters.map({ String($0) })

for letter in alphabet {
    arr_Contacts[String(letter)] = []
    let matches = sortedContact.filter({$0.name.characters.first == letter.characters.first})
    if !matches.isEmpty {
        for contact in matches {
            arr_Contacts[letter]?.append(contact)
        }
    }
}
//Dic are unordered data, so need to use an Array
let sortedDic = Array(arr_Contacts).sorted{ (s1,  s2) in
    return s1.key < s2.key
}

输出

("A", [Contact, Contact, Contact])("B", [])("C", [])("D", [])("E", [])("F", [Contact])("G", [Contact])("H", [])("I", [])("J", [])("K", [])("L", [])("M", [])("N", [])("O", [])("P", [Contact])("Q", [])("R", [])("S", [])("T", [])("U", [])("V", [Contact])("W", [])("X", [])("Y", [])("Z", [])

正如其他人所说,字典是无序的-如果您需要数据的有序表示,则您选择了错误的数据结构。 数组更适合于有序表示。

制作字典或简单结构的数组,将起始字母与以该字母开头的联系人数组组合在一起。

func filterArrayAlphabatically(contacts inputContacts: [Contact]) -> [[String: [Contact]]]
{
    //Using this will remove any contacts which have a name not beginning with these letters, is that intended?
    let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters.map({ String($0) })

    // For strings use a localized compare, it does sensible things with accents etc.
    let allContacts = inputContacts.sorted { $0.name.localizedCompare($1.name) == .orderedAscending }

    //Now we're using an array of dictionaries, each of which will have a single key value pair [letter: [Array of contacts]]
    var result = [[String: [Contact]]]()

    for letter in alphabet
    {
        result.append([letter: contacts(beginningWith: letter, from: allContacts)])
    }

    return result
}

func contacts(beginningWith prefix: String, from contactList: [Contact]) -> [Contact] {
    //you could use a filter here for brevity, e.g.
    //let contacts = contactList.filter { $0.name.capitalized.hasPrefix(prefix) }
    //this is short enough to reasonably be used at the call site and not within a function

    var contacts = [Contact]()
    for contact in contactList {
        if contact.name.capitalized.hasPrefix(prefix) {
            contacts.append(contact)
        }
    }
    return contacts
}

let contacts = [Contact(name: "Bob"), Contact(name: "Kate"), Contact(name: "Darling")]
let filteredArray = filterArrayAlphabatically(contacts: contacts)
print(filteredArray)
//[["A": []], ["B": [Contact(name: "Bob")]], ["C": []], ["D": [Contact(name: "Darling")]], ["E": []], ["F": []], ["G": []], ["H": []], ["I": []], ["J": []], ["K": [Contact(name: "Kate")]], ["L": []], ["M": []], ["N": []], ["O": []], ["P": []], ["Q": []], ["R": []], ["S": []], ["T": []], ["U": []], ["V": []], ["W": []], ["X": []], ["Y": []], ["Z": []]]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM