2014-10-08 47 views
0

我有一個名爲People的數組。人物數組包含Person對象。我想基於firstName升序排列數組。Swift上的NSArray排序函數

var people :[Person] = [] 

people.sort { $0.firstName > $1.firstName } 

我得到以下錯誤:

() is not convertible to [Person] 
+0

數組是如何聲明和初始化的? – Ideasthete 2014-10-08 04:17:56

+0

它由Web服務填充。 – 2014-10-08 04:21:11

+0

但它是如何申報的?你可以在你的問題中包含聲明嗎? – Ideasthete 2014-10-08 04:27:04

回答

1

我相信,你只需要初始化時,更明確地指定數組的類型。此代碼的工作原理:

class Person { 
    var firstName: String = "FirstName" 
    var lastName: String = "LastName" 

    init(inputFirstName: String, inputLastName: String) { 
     firstName = inputFirstName 
     lastName = inputLastName 
    } 
} 
var people: [Person] = [Person]() 

people.append(Person(inputFirstName: "A", inputLastName: "B")) 
people.append(Person(inputFirstName: "B", inputLastName: "C")) 
people.append(Person(inputFirstName: "C", inputLastName: "D")) 
people.append(Person(inputFirstName: "D", inputLastName: "E")) 
people.append(Person(inputFirstName: "E", inputLastName: "F")) 
people.append(Person(inputFirstName: "F", inputLastName: "G")) 
people.append(Person(inputFirstName: "G", inputLastName: "H")) 
people.append(Person(inputFirstName: "H", inputLastName: "I")) 

people.sort { $0.firstName > $1.firstName } 
+0

'var people:[Person] = []'在問題中也是如此。知道實際問題是什麼會很有趣。 – 2014-10-08 05:04:37

+0

奇怪。是的,我無法想象爲什麼這個問題中的例子不起作用,但是也許認爲這是基於錯誤信息的區別。也許在Xcode/Swift中的版本差異? – Ideasthete 2014-10-08 05:09:24

+0

可能是另一個臭名昭着的類型推斷錯誤。 – davecom 2014-10-08 05:54:06