1

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??

2 Answers 2

2

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 }
Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

Answers are more helpful (to the author of the question and to future readers of this thread) if they explain the problem and the solution, instead of posting code only.
ok.. in this answer, we are mapping the string (as per requirement) value in the json as an assignment to the variable. Please see link below: codeburst.io/swift-map-flatmap-filter-and-reduce-53959ebeb6aa
How do I write a good answer?. Commentary to clarify the answer, belongs in the answer, not a comment. Additionally, you've only retyped the contents of an answer posted prior to this post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.