xcode 在 swift 上覆盖 NSObject 中的描述方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30967182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 07:21:09  来源:igfitidea点击:

Overriding description method in NSObject on swift

xcodeswift

提问by Juan Garcia

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

当我尝试在我的 xcode 项目中构建一个对象时,我遇到了一个编译器错误。这是代码:

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?

我需要做什么才能毫无问题地覆盖此功能?

回答by Martin R

  • descriptionis 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 overrideexplicitly.
  • description是 的(计算)属性NSObjectProtocol,而不是方法。
  • 它的 Swift 视图返回一个String,而不是NSString
  • 由于您要覆盖超类的属性,因此必须override明确指定。

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