0

How do I join an array value to a string? I tried the following but got bad instruction error, appreciate any help. Sorry if my code looks bad as I'm still a student new to swift, hehe.

if let jsonData = try JSONSerialization.jsonObject(with: unwrappedData, options: .allowFragments) as? [String:Any] {
    if let test = jsonData["firstname"] as? String {
        let postString = "type=" + jsonData["firstname"] + "&type=insert"
    }
}
5
  • 1
    If you already have jsonData["test"] conditionally bound to test, why do you use it, rather than test? Commented Sep 6, 2017 at 18:59
  • Hi, is just a test post to the server with my php script. It returns json and I'm trying to access its array. Commented Sep 6, 2017 at 19:01
  • You didn't answer my question Commented Sep 6, 2017 at 19:02
  • Sorry I don't get what you mean? Because actually jsonData["test"] is a firstname. Sorry as the variable name is abit confusing. I will change to better illustrate Commented Sep 6, 2017 at 19:05
  • You took the expression jsonData["firstname"] as? String, and you conditionally bound its result to the variable test. But within that if let block, you use jsonData["firstname"], and not the test variable that you just bound Commented Sep 6, 2017 at 19:18

1 Answer 1

1

Try changing

let postString = "type=" + jsonData["firstname"] + "&type=insert"

to

let postString = "type=" + test + "&type=insert"

since you are assigning the non-nil value to test

Let me know if this helps!

Sign up to request clarification or add additional context in comments.

7 Comments

Hi thanks for the reply. I tried and now I've got the error EXC_BAD_INSTRUCTION which is the same error I've got previously.
Also got this in the log fatal error: unexpectedly found nil while unwrapping an Optional value
Is your object being correctly serialized by JSONSerialization ?
It could be because unwrappedData is nil, and you are telling JSONSerialization to serialize an object, which is nil. Check the definition of your unwrappedData, maybe it is nil. Try adding the line if let data = unwrappedData { print("unwrappedData not nil") } above your code. Does it print the statement inside the if clause?
I tried to print(jsonData) and this is what php returns me: ["type": Bearer, "firstname": john, "lastname":"depp"]. Is it something I did wrong in PHP?
|

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.