You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 5:如何映射对象数组适配React Native回调需求?

Swift 转换 Endpoint 对象数组为字典数组适配 React Native 回调

直接使用 Swift 的 map 方法遍历 Endpoint 对象数组,提取所需属性组装成字典即可,代码示例如下:

1. 假设 Endpoint 类定义

class Endpoint {
    let name: String
    let uniqueID: Int
    
    init(name: String, uniqueID: Int) {
        self.name = name
        self.uniqueID = uniqueID
    }
}

2. 在 getDevices 方法中完成转换

func getDevices() -> [[String: Any]] {
    // 此处替换为实际获取的 Endpoint 对象数组
    let devices: [Endpoint] = [
        Endpoint(name: "first", uniqueID: 39),
        Endpoint(name: "second", uniqueID: 28)
    ]
    
    // 映射为目标字典数组
    let mappedDevices = devices.map {
        ["name": $0.name, "uniqueID": $0.uniqueID]
    }
    
    return mappedDevices
}

3. 使用示例(打印或回调给 React Native)

let formattedDevices = getDevices()
print(formattedDevices)
// 输出:[["name": "first", "uniqueID": 39], ["name": "second", "uniqueID": 28]]

这样转换后的数组就不带 Endpoint 前缀,完全符合需求格式,可直接用于 React Native 回调或打印。

内容的提问来源于stack exchange,提问作者Jeremy Seigle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 03:45:49