Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot convert value of type Substring to expected argument type String - Swift 4

Tags:

swift

swift4

Trying to get substring of String and append it to array of Strings:

var stringToSplit = "TEST TEXT"
var s = [String]()
let subStr = anotherString[0 ..< 6]
s.append(subStr) // <---- HERE I GET THE ERROR

error desc

like image 529
MBH Avatar asked Sep 22 '17 06:09

MBH


2 Answers

As @Leo Dabus mentioned, you need to initialize a new String with your substring:

Change:

s.append(subStr)

To:

s.append(String(subStr))
like image 188
Rashwan L Avatar answered Nov 17 '22 09:11

Rashwan L


my two cents for serro in different context. I was trying to get an array of "String" splitting a string. "split" gives back "Substring", for efficiency reason (as per Swift.org litre).

So I ended up doing:

let buffer = "one,two,three"
let rows = buffer.split(separator:",")

let realStrings = rows.map { subString -> String in
    return String(subString)
}

print(realStrings)

Ape can help someone else.

like image 2
ingconti Avatar answered Nov 17 '22 07:11

ingconti