本文介绍了在 swift 上覆盖 NSObject 中的描述方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

编译时的错误是:

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?

推荐答案

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

      // 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
      

      这篇关于在 swift 上覆盖 NSObject 中的描述方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 01:59