Cannot convert value of type 'subSequence' (aka 'String.CharacterView') to type 'String' in collection

Viewed 45954

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:

Cannot convert value of type 'subSequence' (aka 'String.CharacterView') to type 'String' in collection

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!) {
    ...
}
5 Answers

The easiest solution.

let separated = requestResponse.characters.split(separator: " ").map { String($0) }

If swift 4 you use like this:

let separated = requestResponse.split(separator: " ")
var photo = String(separated.first ?? "")

split returns a list of Substrings, so we have to map (convert) them to Strings. To do that you can just pass the Substring to the Strings init function:

let separated = requestResponse.characters.split(separator: " ").map(String.init)

An approach to obtain strings from splitting a string using high order functions:

let splitStringArray = requestResponse.split(separator: " ").map({ (substring) in
    return String(substring)
})
Related