4

Need to convert array of string value to array of URL. Some one help me to convert the String array to URL array in swift.

2 Answers 2

13
let urls = ["www.1.com", "www.1.com", "www.1.com", "randomSmth"].compactMap { URL(string: $0) }

"compactMap" ensures that it just ignores invalid urls.

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

1 Comment

Upvoting your answer because you were the first to provide a valid solution that didn't include force unwrapping (a ton of duplicates just appeared). This should be marked as the correct answer.
1

Use compact map to filter non valid URLs


let arrayOfStrings = ["https://www.google.com","https://www.facebook.com", "notRerallyAnURL"]
let arrayOfURLs = arrayOfStrings.compactMap { URL(string:$0) }

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.