Leo
Leo

Reputation: 862

How to convert json into String array

Hi I'm very new to Swift and I'm trying to make a simple application.

The app gets data from server as JSON format.

func addLangList(completion: @escaping ([String], [String]) -> Void) {

    let request = NetworkRequest()
    let reqUrl = NetworkInformation.serverAddr + "/word/purpose"
    let parameters: Parameters = ["category": "lang"]
    request.sendGetRequest(url: reqUrl, parameters: parameters, success: { (response) in

        let json = JSON(response)
        let isSuccess = json[ServerResponseKey.KEY_RESULT]


        if isSuccess == true {

            var resultMessage:JSON = json[ServerResponseKey.KEY_MESSAGE]

            let lang = resultMessage["lang"].arrayValue
            let purpose = resultMessage["purpose"].arrayValue


            completion(lang, purpose)
        }

    }, fail: request.CommonNetworkFailureHandler)
}

By using Swiftyjson, the function converts the data received into JSON format. Inside the closure, 'completion' is called for further process in caller. An error occurs at 'completion(lang, purpose). Xcode says

" Cannot convert value of type '[JSON]' to expected argument type '[String]'".

The error, I guess, because .arrayValue doesn't change resultMessage["lang"] into [String] type....Can anyone give me some advice??

Upvotes: 1

Views: 81

Answers (2)

Creign
Creign

Reputation: 134

let langStr = lang.map { $0.string }
let purposeStr = purpose.map { $0.string }

Upvotes: 1

Shehata Gamal
Shehata Gamal

Reputation: 100503

Those 2 arrays

let lang = resultMessage["lang"].array
let purpose = resultMessage["purpose"].array

are of type JSON which isn't String , you need to cast them

let langStr = lang.map { $0.string }
let purposeStr = purpose.map { $0.string }

Upvotes: 2

Related Questions