Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overriding description method in NSObject on swift

Tags:

xcode

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?

like image 829
Juan Garcia Avatar asked Jun 21 '15 17:06

Juan Garcia


1 Answers

  • 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
like image 93
Martin R Avatar answered Oct 02 '22 15:10

Martin R