2

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?

Naijaba
  • 1,019
  • 1
  • 13
  • 24

2 Answers2

2
  • You defined the parameter s as non optional String. A non optional type can never be nil, that's why the compiler complains.
    Just remove the checking for nil.

  • You defined the return type as a non optional String.
    Either you have to unwrap the result value to conform to the type

    func escape(s: String) -> String
    {
      return s.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())!
    }
    

    or change the return type to an optional

    func escape(s: String) -> String?
    {
      return s.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet())
    }
    
vadian
  • 274,689
  • 30
  • 353
  • 361
1

Not a minute after posting I read deeper into the docs. stringByAddingPercentEncodingWithAllowedCharacters CAN return a nil value, even given a non-nil value. From https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/#//apple_ref/occ/instm/NSString/stringByAddingPercentEncodingWithAllowedCharacters

Return Value Returns the encoded string, or nil if the transformation is not possible.

Discussion UTF-8 encoding is used to determine the correct percent encoded characters. Entire URL strings cannot be percent-encoded.

Naijaba
  • 1,019
  • 1
  • 13
  • 24