how to parse string array with SwiftyJSON?

后端 未结 4 2106
长情又很酷
长情又很酷 2020-12-13 06:29

Using SwiftyJSON how would I parse the following JSON array into a Swift [String]?

{
    \"array\": [\"one\", \"two\", \"three\"]
}         


        
4条回答
  •  北海茫月
    2020-12-13 06:53

    SwiftyJSON lets you extract a String? using $0.string or a non optional String using stringValue with a default empty String value if the type doesn't match.

    If you want to be sure to have an array of String with non false positives, use :

    var stringArray = self.json["array"].array?.flatMap({ $0.string })

    or in Swift 4.1

    var stringArray = self.json["array"].array?.compactMap({ $0.string })

    You can also replace self.json["array"].array by self.json["array"].arrayValue to have a [String] result instead of [String]?.

提交回复
热议问题