我有一个[AnyObject]
数组,并希望将其转换为[PFObject]
和[String]
。这样做的正确方法是什么?我被告知as String
不是从AnyObject
转发的理想方式。
目前使用此代码将数组中的对象转换为String:
restaurantNames = finalRestaurantArray.map { $0.objectForKey("Name") as String }
数组如下所示:
[<Restaurant: 0x7feb9252cfc0, objectId: LA74J92QDA, localId: (null)> {
Name = "Restaurant 1";
City = "New York";
Closed = 1;
Country = "United States";
FoodType = Japanese;
}, <Restaurant: 0x7feb926afa00, objectId: 0aKFrpKN46, localId: (null)> {
Name = "Restaurant 2";
City = "San Francisco";
Closed = 1;
Country = "United States";
FoodType = Italian;
}]
答案 0 :(得分:3)
您可以使用以下内容:
let restaurantNames = finalRestaurantArray.map {
$0["Name"] as? String ?? ""
}
如果向下转发失败,??
会设置默认值。