我跟随苹果示例项目TVAnimationsGestures,但将其应用于我自己的一个项目。我需要将plist中的数据加载到我的类中,但我似乎无法弄清楚如何在swift中完成它。这是一个试图阅读的plist的图像。
示例项目使用此方法读取plist
- (NSArray *)plays {
if (_plays == nil) {
NSURL *url = [[NSBundle mainBundle] URLForResource:@"PlaysAndQuotations" withExtension:@"plist"];
NSArray *playDictionariesArray = [[NSArray alloc ] initWithContentsOfURL:url];
_plays = [NSMutableArray arrayWithCapacity:[playDictionariesArray count]];
for (NSDictionary *playDictionary in playDictionariesArray) {
APLPlay *play = [[APLPlay alloc] init];
play.name = playDictionary[@"playName"];
NSArray *quotationDictionaries = playDictionary[@"quotations"];
NSMutableArray *quotations = [NSMutableArray arrayWithCapacity:[quotationDictionaries count]];
for (NSDictionary *quotationDictionary in quotationDictionaries) {
APLQuotation *quotation = [[APLQuotation alloc] init];
[quotation setValuesForKeysWithDictionary:quotationDictionary];
[quotations addObject:quotation];
}
play.quotations = quotations;
[_plays addObject:play];
}
}
return _plays;
}
我环顾四周,并设法让大部分内容没有显示任何错误,但我认为它没有正确完成,因为有大量的投射。这是我有多远:
func loadFoodCategoryData() ->[Any] {
// foodCategoryData is declared outside the function
if foodCategoryData == nil {
var url = NSBundle.mainBundle().URLForResource("Items", withExtension: "plist")!
var categoryDictionaryArray = NSArray(contentsOfURL: url) as! [[String:AnyObject!]]
foodCategoryData = Array()
for foodDictionary:Dictionary in categoryDictionaryArray {
var foodCat = FoodCategories()
foodCat.foodCategoryName = foodDictionary["categoryName"] as! String
var foodItemsDict = foodDictionary["items"]
var foodItemsArray = [AnyObject]()
for foodItems in foodDictionary {
var foodItem:FoodItems = FoodItems()
foodItem.setValuesForKeysWithDictionary(foodItems as! Dictionary)
foodItemsArray.append(foodItem)
}
}
}
return foodCategoryData
}
任何人都有更好更有效的方法将这个plist加载到我的课程中?
答案 0 :(得分:0)
延迟初始化变量在Swift中具有特定语法。与ObjC代码等价的是(简化了主体)
lazy var plays : [AnyObject] = {
var foodCategoryData = [AnyObject]()
// do things
foodCategoryData.append("something")
return foodCategoryData
}()
来自AnyObject的压缩是一种痛苦,但却是必要的
修改强>
您的代码非常接近。试试这个(未经测试的)
lazy var foodCategoryData : [AnyObject] = {
let url = NSBundle.mainBundle().URLForResource("Items", withExtension: "plist")!
var categoryDictionaryArray = NSArray(contentsOfURL: url) as! [[String:AnyObject!]]
var foodItemsArray = [FoodItems]()
for foodDictionary in categoryDictionaryArray {
var foodCat = FoodCategories()
foodCat.foodCategoryName = foodDictionary["categoryName"] as! String
var foodItemsDict = foodDictionary["items"] as! [String:AnyObject]
for foodItems in foodDictionary {
var foodItem:FoodItems = FoodItems()
foodItem.setValuesForKeysWithDictionary(foodItems as! Dictionary)
foodItemsArray.append(foodItem)
}
}
return foodItemsArray
}()