Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic parameter 'Self' could not be inferred (swift 4)

Tags:

xcode

swift4

I want to make a substring extension for string , I tried below 2 ways but unsuccessful:

extension String
{
    func substringToFirstChar(of char: Character) -> String
    {
        let pos = self.range(of: String(char))
        let subString = self[..<pos?.lowerBound]   
        return String(subString)
    }
}

or

extension String
{
    func substringToFirstChar(of char: Character) -> String
    {
        let pos = self.index(of: char)
        let subString = self[..<pos]
        return String(subString)
    }
}

xcode prompt error: Generic parameter 'Self' could not be inferred at the "let subString = self[.." line.

How to do that ?

like image 766
Haiyuan Avatar asked Jan 05 '18 11:01

Haiyuan


1 Answers

range(of / index(of returns an optional. You have to unwrap the optional in the range expression

extension String
{
    func substringToFirstChar(of char: Character) -> String?
    {
        guard let pos = self.range(of: String(char))?.lowerBound else { return nil }
        // or  guard let pos = self.index(of: char) else { return nil }
        let subString = self[..<pos]
        return String(subString)
    }
}

alternatively – to avoid the optional – return the unchanged string if there is no match

extension String
{
    func substringToFirstChar(of char: Character) -> String
    {
        guard let pos = self.range(of: String(char))?.lowerBound else { return self }
        // or  guard let pos = self.index(of: char) else { return self }
        let subString = self[..<pos]
        return String(subString)
    }
}
like image 181
vadian Avatar answered Sep 27 '22 18:09

vadian