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 ?
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)
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With