【问题标题】:How to declare the model that will work with nested object?如何声明将与嵌套对象一起使用的模型?
【发布时间】:2018-10-29 20:52:24
【问题描述】:

我需要创建一个像这样结构的对象

distances.append([
    "distanceInMiles":String(distanceInMiles),
    "distanceInMeters":String(distanceInMeters),
    "places": [
        {
            "name":nameI,
            "city":cityI,
            "lat":latitudeI,
            "lon":longitudeI,
            "coordinate":coordinateI
        }, {
            "name":nameJ,
            "city":cityJ,
            "lat":latitudeJ,
            "lon":longitudeJ,
            "coordinate":coordinateJ
        }
    ]
])

我的变量声明应该是什么?

我试过了

var distances = [ Dictionary<String,String>()]

我明白了

参数标签 '(_:, _:)' 不匹配任何可用的重载

如何进一步调试?

【问题讨论】:

  • 让您的生活更方便,使用自定义结构/类。
  • 我想我知道你的问题是什么。你能确切地澄清你在努力解决什么问题吗?您不确定如何为此对象创建init() 方法吗?
  • @vadian i.imgur.com/nUZq2pM.png 喜欢这样吗?
  • 差不多:distanceIn...可以是原始类型(IntDouble),places可以是非可选的并且必须是一个数组@987654329 @,所有结构成员都可以是常量(let)。
  • 你到底想在这里实现什么?感觉你唯一需要的就是这两个地方的名称和坐标。其他一切都可以从该信息中计算出来

标签: arrays json swift object


【解决方案1】:

只需为如此复杂的结构编写一个结构/类即可:

struct Distance { // You might want to find a better name
    let distanceInMiles: Double
    let distanceInMeters: Double
    let places: [Place]
}

struct Place {
    let name: String
    let city: String
    let lat: Double
    let long: Double
    let coordinate: CLLocationCoordinate2D // You might want to make this a computed property instead
}

然后你可以创建一个Distance 数组:

var distances = [Distance]()
distance.append(Distance(
    distanceInMiles: distanceInMiles,
    distanceInMeters: distanceInMeters,
    places: [
        Place(name: nameI, city: cityI, lat: latitudeI, long: longitudeI, coordinate: coordinateI),
        Place(name: nameJ, city: cityJ, lat: latitudeJ, long: longitudeJ, coordinate: coordinateJ),
    ]
))

如您所见,美学与您的类 JSON 结构非常相似。

顺便说一句,如果您打算将此结构转换为 JSON 并将其发送到某个地方,则可以使两个结构都符合 Codable

【讨论】:

  • 你是我的英雄! ?
  • 我只看到 1 个问题,我收到了 Cannot convert value of type 'CLLocation' to expected argument type 'CLLocationCoordinate2D' i.imgur.com/IBALwcE.png
  • @kyo 在CLLocation 中有一个名为coordinate 的属性。使用:coordinateI.coordinate。或者,完全删除 coordinate 属性,因为您可以从 latlong 获取它,不是吗?
  • @kyo 或者,在 CLLocation 类型的结构中创建 coordinate 属性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-23
  • 1970-01-01
  • 2019-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-20
相关资源
最近更新 更多