Question or problem with Swift language programming:
I build a webservis that requesting image url from the database. And I want to show it on the swift. But I’m gettig this error on the var photo line:
let requestResponse = self.sendToServer(postUrl: "localhost",data:"abc") let Seperated = requestResponse.characters.split(separator: " ") var photo = Seperated[0] as String let imageURL = URL(string: photo) if let imageData = try? Data(contentsOf: imageURL!) { ... }
How to solve the problem:
Solution 1:
Consider something like this:
let requestResponse = "some string" let separated = requestResponse.characters.split(separator: " ") if let some = separated.first { let value = String(some) // Output: "some" }
Solution 2:
The easiest solution.
let Seperated = requestResponse.characters.split(separator: " ").map { String($0) }
Solution 3:
If swift 4 you use like this:
let separated = requestResponse.split(separator: " ") var photo = String(separated.first ?? "")
Solution 4:
An approach to obtain strings from splitting a string using high order functions:
let splitStringArray = requestResponse.split(separator: " ").map({ (substring) in return String(substring) })
Solution 5:
split
returns a list of Substring
s, so we have to map (convert) them to String
s. To do that you can just pass the Substring
to the String
s init
function:
let separated = requestResponse.characters.split(separator: " ").map(String.init)