I'm relatively new to Swift and I've been wrapping my head around optional variables. Here's the issue I've run into:
func escape(s: String) -> String
{
if s == nil
{
return ""
}
return s.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
}
The compiler complains that:
Value of type 'String' can never be nil, comparison isn't allowed
This is in reference to the if s == nil
line. If I remove the if statement line and just have the return value line, I get the error:
Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'
I see in the docs that stringByAddingPercentEncodingWithAllowedCharacters returns a String? parameter. I don't understand why this isn't forced to be a String? Since a String can't be nil, I can't pass nil to this function, so how would it return nil?