求助:使用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 SwiftStringusingstringValue, 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 usemapinstead, butcompactMapadds 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.
相关产品推荐
相关产品推荐

