简体   繁体   English

从 Swift 中解码的 JSON 中提取字符串数组

[英]Extract Array of Strings from Decoded JSON in Swift

I am using JSONDecoder to decode JSON obtained from an API into an array of objects each of which contains a key value pair of interest.我正在使用 JSONDecoder 将从 API 获得的 JSON 解码为一个对象数组,每个对象都包含一个感兴趣的键值对。 For that key, I would like to obtain an array of the values (that are strings).对于该键,我想获得一个值数组(即字符串)。 The JSON decodes fine into an array, however, I cannot extract an array of values for the key I'm interested in using Array[key]. JSON 可以很好地解码成一个数组,但是,我无法使用 Array[key] 为我感兴趣的键提取值数组。 What am I doing wrong?我究竟做错了什么?

Starting JSON looks like:启动 JSON 看起来像:

[{"word":"hi"},{"word":"howdy"},{"word":"hullo"}]

My code:我的代码:

struct Synonym: Codable {
        let word: String
    }
typealias Synonyms = [Synonym]
//Code to create session etc and get data
let mysynonyms = try? JSONDecoder().decode(Synonyms.self, from: data) 

//everything works fine up to here
var words = mysynonyms?[word]! //THROWS ERROR Use of unresolved identifier 'word'

Would appreciate any suggestions into why the last line does not work.将不胜感激任何关于为什么最后一行不起作用的建议。

var words = (mysynonyms?? []).map { $0.word }

Using the [] subscript syntax on a type (struct/class) doesn't work in Swift -- instead, you need to use the dot syntax to get the property.在类型(结构/类)上使用[]下标语法在 Swift 中不起作用——相反,您需要使用点语法来获取属性。 And, since you want all of the words, you can use map to transform the array.而且,由于您想要所有单词,您可以使用map来转换数组。

I'm also using the ??我也在用?? to say "if mysynonyms is nil, map an empty array instead" so words will be [] in the event that mysynonyms was nil .要说“如果mysynonyms为 nil,则 map 为空数组”,因此如果mysynonymsnil ,则words将为[]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM