Juan Garcia
Juan Garcia

Reputation: 855

Overriding description method in NSObject on swift

I'm getting one compiler error when I try to build one object in my xcode project. This is the code:

import UIKit

class Rectangulo: NSObject {

    var ladoA : Int
    var ladoB : Int
    var area: Int {
        get {
            return ladoA*ladoB
        }
    }

    init (ladoA:Int,ladoB:Int) {

        self.ladoA = ladoA
        self.ladoB = ladoB
    }

    func description() -> NSString {
                return "El area es \(area)"
    }
}

The error in compilation time is:

Rectangulo.swift:26:10: Method 'description()' with Objective-C selector 'description' conflicts with getter for 'description' from superclass 'NSObject' with the same Objective-C selector

What I need to do to override this function without issues?

Upvotes: 15

Views: 12189

Answers (1)

Martin R
Martin R

Reputation: 539845

  • description is a (computed) property of NSObjectProtocol, not a method.
  • Its Swift view returns a String, not NSString.
  • Since you are overriding a property of a superclass, you must specify override explicitly.

Together:

// main.swift:
import Foundation

class Rectangulo: NSObject {

    var ladoA : Int
    var ladoB : Int
    var area: Int {
        get {
            return ladoA*ladoB
        }
    }

    init (ladoA:Int,ladoB:Int) {

        self.ladoA = ladoA
        self.ladoB = ladoB
    }

    override var description : String {
        return "El area es \(area)"
    }
}

let r = Rectangulo(ladoA: 2, ladoB: 3)
print(r) // El area es 6

Upvotes: 27

Related Questions