【问题标题】:Converting a JSValue to a typed array将 JSValue 转换为类型化数组
【发布时间】:2020-01-10 19:50:07
【问题描述】:

我正在编写一个 tvos 应用程序,它有一个函数,我的 tvml 调用一个对象数组。

如何正确地将 json 转换为某种类型/接口的数组?

// This type is generated from my TypeScript types
struct Video: Codable {
    let title: String

    enum CodingKeys: String, CodingKey {
        case title
    }
}

{
      func appController(_ appController: TVApplicationController, evaluateAppJavaScriptIn jsContext: JSContext) {
        let playVideo : @convention(block) (Int, JSValue) -> Void = {
            (start, json) -> Void in
            // How do I properly cast the json to an array of Videos?
            let playlist = json;

            for video in playlist {
                // here I would like to access video.title
                print(video)
            }
        }

        jsContext.setObject(unsafeBitCast(playVideo, to: AnyObject.self),
                            forKeyedSubscript: "playVideo" as (NSCopying & NSObjectProtocol))
    }
}

PS:我是一个 swift/objc 新手。

【问题讨论】:

标签: swift


【解决方案1】:

我想我明白了。看来我只需要使用AnyHashable

let playlist = json.toArray() as! [[AnyHashable:Any]];

for video in playlist {
  print(video[AnyHashable("title")])
}

虽然这仍然没有使用我定义的类型

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 2011-02-05
    • 2013-09-02
    • 2013-05-01
    • 2023-03-15
    相关资源
    最近更新 更多