0

Cannot invoke to != nil in xcode 6.1 generating error

func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) {

    if(elementName as NSString).isEqualToString("item"){
        if ftitle != nil{
        elements.setObject(self.ftitle, forKey: "title")
        }
        if link != nil {
            elements.setObject(self.link, forKey: "link")
        }
        if fdescription  != nil{
        elements.setObject(self.fdescription, forKey: "description")
        }

        feeds.addObject(elements)
    }
}
Cœur
  • 37,241
  • 25
  • 195
  • 267

3 Answers3

1

If ftitle, link and fdescription are not Optional you cannot compare them to nil.

var str1:String?
var str2:String = "a"

if str1 != nil{ } // OK

if str2 != nil{ } // ERROR (Cannot invoke '!=' with an argument ....)

See explanation here What is an optional value in swift

Community
  • 1
  • 1
Maxim Shoustin
  • 77,483
  • 27
  • 203
  • 225
1

I think ftitle , link and fdescription are not optionals.

If I assume ftitle is a String,

I would declare it as

var ftitle  : String?

Then you can check != nil or you can you can unwrap it like

if let temp = ftitle{

}
toofani
  • 1,650
  • 13
  • 16
0

Non-optional values cannot be compared to nil because they cannot be nil that's the entire idea behind optional and non-optional,

if you think that at any place your variable may or may not hold any value then you should declare your variable as optional and not non-optional.

Below code sample shows an example of optional string

var myOptionalStringType:String? = "NSDumb"

if (myOptionalStringType != nil) {
println("It's not nil")
}else{
println("its nil")
}

I suggest reading this blog on optional type that would help you out on when you should use optional types.

Bug Hunter Zoro
  • 1,743
  • 18
  • 21