arrays - 如何初始化信息数组并追加

标签 arrays swift dictionary

我希望能够初始化一个空数组结构,该结构具有 .append() 的能力并且可以保存类似于以下的信息:

var locations = [
    ["title": "New York, NY",    "latitude": 40.713054, "longitude": -74.007228],
    ["title": "Los Angeles, CA", "latitude": 34.052238, "longitude": -118.243344],
    ["title": "Chicago, IL",     "latitude": 41.883229, "longitude": -87.632398]
]

这个数据类型是字典数组的数组吗?我希望能够通过 location 访问 titlelatitudelongitude 并且我从未使用过像这样,所以我不确定如何初始化和 .append()

最佳答案

您的结构是字典数组:[[String : Any]]

正如@Hamish 在评论中建议的那样,最好将数据存储为结构数组。

这是一种可能的实现方式:

struct Location: CustomStringConvertible {
    var title: String
    var latitude: Double
    var longitude: Double

    var description: String { return "(title: \(title), latitude: \(latitude), longitude: \(longitude))"}
}

var locations = [
    Location(title: "New York, NY", latitude: 40.713054, longitude: -74.007228),
    Location(title: "Los Angeles, CA", latitude: 34.052238, longitude: -118.243344),
    Location(title: "Chicago, IL", latitude: 41.883229, longitude: -87.632398)
]

// Append a new location...    
locations.append(Location(title: "Boston, MA", latitude: 42.3601, longitude: -71.0589))

print(locations)
[(title: New York, NY, latitude: 40.713054, longitude: -74.007228),
(title: Los Angeles, CA, latitude: 34.052238, longitude: -118.243344),
(title: Chicago, IL, latitude: 41.883229, longitude: -87.632398),
(title: Boston, MA, latitude: 42.3601, longitude: -71.0589)]
func lookUp(title: String, in locations: [Location]) -> [Location] {
    return locations.filter { $0.title.range(of: title) != nil }
}

print(lookUp(title: "CA", in: locations))
[(title: Los Angeles, CA, latitude: 34.052238, longitude: -118.243344)]
print(lookUp(title: "Chicago", in: locations))
[(title: Chicago, IL, latitude: 41.883229, longitude: -87.632398)]

关于arrays - 如何初始化信息数组并追加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41523857/

相关文章:

c - char s[] 和 char *s 在初始化方面有什么区别?

ios - APNs 身份验证 key 是否会过期?

python - 将操作应用于字典中的所有数据帧,无需循环

scala - Scala 2.8.0 和 2.7.7 中 Map 行为的这种令人惊讶的差异(对我来说)是预期的吗?

c# - .NET 字典中的元素是连续的吗?

php - 将数组保存到数据库 mysql/php

jquery - 在jquery中使用ajax发布一个空数组

ios - Swift 中错误转换的问题

ios - 为我的变量编写自定义 Setter - Swift

javascript - 对象、数组或类数组对象