我对底部的最后几行代码感兴趣 - 不是在寻找对类的批评。那些就在那里,所以你有一些代码可以试验。有没有办法把它们放在一起?似乎还有很长的路要走但却无法弄清楚如何让它变得更好。我真的不需要间歇性批次的allobjects,只需要排序的那些。
import Foundation
class AnItem: NSObject {
var theString: String = ""
}
class GroupOfItems: NSObject {
var title: String = ""
var lotsOfItems = NSSet()
init(withTitle: String, andInitialValue value: String) {
super.init()
title = withTitle
addNewItemToList(withValue: value)
}
func addNewItemToList(withValue value: String) -> Int {
let freshItem = AnItem()
freshItem.theString = value
lotsOfItems = lotsOfItems.adding(freshItem) as NSSet
return lotsOfItems.count
}
}
var myGroup = GroupOfItems(withTitle: "My title", andInitialValue: "First item")
myGroup.addNewItemToList(withValue: "Second item")
myGroup.addNewItemToList(withValue: "Third item")
var anArrayOfItems = myGroup.lotsOfItems.allObjects as! [AnItem]
anArrayOfItems = anArrayOfItems.sorted(by: { (s1: AnItem, s2: AnItem) -> Bool in
return s1.theString < s2.theString
})