Abid Ali
Abid Ali

Reputation: 1

Cannot invoke to != nil in xcode 6.1 generating error

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)
    }
}

Upvotes: 0

Views: 68

Answers (3)

Bug Hunter Zoro
Bug Hunter Zoro

Reputation: 1915

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.

Upvotes: 0

Sarvjeet Singh
Sarvjeet Singh

Reputation: 1680

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{

}

Upvotes: 1

Maxim Shoustin
Maxim Shoustin

Reputation: 77904

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

Upvotes: 1

Related Questions