user2976267 user2976267 - 3 months ago 17
Swift Question

Cannot invoke 'append' with an argument list of type '(String)' where every variable is non - optional

I get error

Cannot invoke 'append' with an argument list of type '(String)'
and all the similar questions in StackOverflow says that the reason there is some optional variable but here every variable is non - nullable

private var j : Int!
private var inString : String!
private var outStr : String!

if self.j < self.inString.characters.count{
var substr = self.inString.substringWithRange(
Range<String.Index>(start: self.inString.startIndex.advancedBy(self.j), end: self.inString.endIndex))
self.outStr.append(substr) // Here I got Cannot invoke 'append' with an argument list of type '(String)'
}

Answer

What you are doing is you are appending Character. In String append is used to append Character. While substringWithRange returns String. So, you have to use appendContentsOf.

Method 1:

var j : Int!
var inString : String!
var outStr : String!

if j < inString.characters.count{
   let substr = inString.substringWithRange(inString.startIndex.advancedBy(j)..<inString.endIndex)
   outStr.appendContentsOf(substr) // Solved
}

Method 2:

var j : Int!
var inString : String!
var outStr : String!

if j < inString.characters.count{
    let substr = inString.substringWithRange(inString.startIndex.advancedBy(j)..<inString.endIndex)
    outStr = outStr + substr
}

Also, Range is going to deprecated!