43

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!) {
    ...
}
Paulo Mattos
  • 18,845
  • 10
  • 77
  • 85
U. Demiroz
  • 441
  • 1
  • 4
  • 4

5 Answers5

50

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"
}
Michael
  • 697
  • 5
  • 11
42

The easiest solution.

let separated = requestResponse.characters.split(separator: " ").map { String($0) }
Daniel Storm
  • 18,301
  • 9
  • 84
  • 152
Mickey Mouse
  • 1,731
  • 3
  • 24
  • 40
  • 4
    It took me a while to understand why this was neccesary, but it's because split returns a 'substring' object not a string. It's similar but for speed reasons if you modify a substring it modifies from the original string so it's more memory efficient. So what map does is for each 'substring' converts it to an actual string, which is necessary for a lot of functions. Hope this helps someone else understand why this works some more. – Joseph Astrahan Feb 28 '20 at 02:22
9

If swift 4 you use like this:

let separated = requestResponse.split(separator: " ")
var photo = String(separated.first ?? "")
Guillodacosta
  • 383
  • 3
  • 8
9

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)
Joony
  • 4,498
  • 2
  • 30
  • 39
5

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

let splitStringArray = requestResponse.split(separator: " ").map({ (substring) in
    return String(substring)
})
pkamb
  • 33,281
  • 23
  • 160
  • 191
Juan Ramirez
  • 51
  • 1
  • 4