1

I have an array of name like this

let arrayOfName = ["alex","lonzo","lavar"]

and sometimes my array only has 1 element but it will never be empty

let arrayOfName = ["lavar"]

is there a way that I can display all the names in this string format? For example in the 1st case:

"studentName=alex&studentName=lonzo&studentName=lavar"

and for the 2nd case, it would be

"studentName=lavar"

Thank you very much for your help!

1
  • 1
    FYI - If you are doing this to build a URL with a query string then please look into URLComponents and URLQueryItem. Commented Jun 14, 2018 at 2:56

1 Answer 1

3

Use a map and joined:

let arrayOfName = ["alex","lonzo","lavar"]
let namesResult = arrayOfName.map { "studentName=\($0)" }.joined(separator: "&")
print(namesResult)

Result:

studentName=alex&studentName=lonzo&studentName=lavar

This will work even if the array has zero or one name or any number of names.

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

Comments

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.