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

求助:使用SwiftyJSON将JSON转换为字符串数组问题

SwiftyJSON 转 String 数组解决方案

Hey there! I see you're having trouble converting a SwiftyJSON object to a Swift [String] array for your radioTableView.items — let's get this sorted out quickly.

The Fix

Your answers variable is a SwiftyJSON JSON type, and since your print output confirms it's an array of strings, you can easily convert it to a native Swift string array using SwiftyJSON's built-in properties. Here's how to update your code:

var answers = JSON() { 
    didSet { 
        print(answers) 
        // Convert SwiftyJSON array to [String]
        let stringArray = answers.arrayValue.compactMap { $0.stringValue }
        radioTableView.items = stringArray
        radioTableView.reloadData() 
    } 
}

Why This Works

Let's break down the key parts:

  • arrayValue: This safely extracts the underlying array from the SwiftyJSON object. If the JSON isn't an array (for some edge case), it returns an empty array instead of crashing your app.
  • compactMap { $0.stringValue }: This loops through each element in the JSON array, converts it to a Swift String using stringValue, and filters out any elements that can't be converted to a string (though your print output suggests this won't be an issue here). If you're 100% sure every element is a string, you could use map instead, but compactMap adds a nice safety layer.

Quick Check

After making this change, your radioTableView.items will be populated with the exact string array you need (["ans1", "ans2", "ans3"]), just like your commented-out example.

内容的提问来源于stack exchange,提问作者noxo.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 08:42:50