簡體   English   中英

'[NSObject]' 不能轉換為 '[AnyObject]'

[英]'[NSObject]' is not convertible to '[AnyObject]'

我正在嘗試創建 tableview,其中正在對數組進行排序並將其放入相應的部分。 我跟着這個教程: http : //www.yudiz.com/creating-tableview-with-section-indexes/

我設法使第一個工作在 tableview 數組被排序的地方,即使沒有數據的部分仍然出現。

第二個是關於解決仍然出現沒有數據的部分的問題,這對我不起作用。

在跟隨第二個之后,由於此錯誤,我無法運行它

'[MyContact]' is not convertible to '[AnyObject]'

這是我的代碼:

聯系方式:

class MyContact: NSObject {
    @objc var name: String!
    @objc var mobile: String!

    init(name: String, mob: String) {
        self.name = name
        self.mobile = mob
    }
}

將數組划分為已排序的子類別的擴展

extension UILocalizedIndexedCollation {

    func partitionObjects(array: [AnyObject], collationStringSelector: Selector) -> ([AnyObject], [String]) {
        var unsortedSections = [[AnyObject]]()

        for _ in self.sectionTitles {
            unsortedSections.append([])
        }

        for item in array {
            let index: Int = self.section(for: item, collationStringSelector: collationStringSelector)
            unsortedSections[index].append(item)
        }
        var sectionTitles = [String]()
        var sections = [AnyObject]()
        for index in 0 ..< unsortedSections.count {
            if unsortedSections[index].count > 0 {
                sectionTitles.append(self.sectionTitles[index])
                sections.append(self.sortedArray(from: unsortedSections[index], collationStringSelector: collationStringSelector) as AnyObject)
            }
        }
        return (sections, sectionTitles)
    }
}

數據源的元組和有錯誤的行

let (arrayContacts, arrayTitles) = collation.partitionObjects(array: self.myContacts, collationStringSelector: #selector(getter: MyContact.name)) as! [[MyContact]]

您正在嘗試將元組強制轉換為數組數組。

let (arrayContacts, arrayTitles) = collation.partitionObjects(array: self.myContacts, collationStringSelector: #selector(getter: MyContact.name))

將返回類型為([AnyObject], [String])的元組。

此外,您不應該使用AnyObject除非您確實需要將某些東西作為class類型。 你可以這樣重寫:

extension UILocalizedIndexedCollation {
    func partitionObjects(array: [Any], collationStringSelector: Selector) -> ([Any], [String]) {
        var unsortedSections = [[Any]](repeating: [], count: self.sectionTitles.count)

        for item in array {
            let index = self.section(for: item, collationStringSelector: collationStringSelector)
            unsortedSections[index].append(item)
        }
        var sectionTitles = [String]()
        var sections = [Any]()
        for index in 0..<unsortedSections.count {
            if unsortedSections[index].isEmpty == false {
                sectionTitles.append(self.sectionTitles[index])
                sections.append(self.sortedArray(from: unsortedSections[index], collationStringSelector: collationStringSelector))
            }
        }
        return (sections, sectionTitles)
    }
}

這樣你就可以將MyContact寫成一個struct ,它仍然可以使用這個函數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM