Swift 3.0扩展 - 未在Child class

时间:2017-05-12 04:55:31

标签: ios swift swift3 extension-methods

当我将代码从swift 2.3转换为swift 3.0时,我遇到了Extension实现问题。 问题陈述: -

1)每个继承的类要求协议实现

2)无法调用已在Extension中实现的方法。

请查看以下代码以获取更多理解。

  protocol MyExtension {
        static func addTwoNumber(number1: Double, number2: Double)
    }

    extension MyExtension {
        static func addTwoNumber(number1: Double, number2: Double) {
          //implementation
      }

        static func subTractTwoNumbers(number1: Double, number2: Double) {
         //implementation
      }
    }

    internal class firstClass: MyExtension {
         static func multiplyTwoNumbers(number1: Double, number2: Double) {
        //implementation
        // if I call subTractTwoNumbers in this class it is giving me an error    
          subTractTwoNumbers(10, 10)
        //and asking me to implement protocol method as well ie 
        //static func addTwoNumber(number1: Double, number2: Double)
      }
    }

请让我知道,我做错了什么。

2 个答案:

答案 0 :(得分:0)

替换此

subTractTwoNumbers(10, 10)

使用

subTractTwoNumbers(number1: 10, number2: 10) // you must have to pass the argument lables name to call the function.

如果您不想要参数的参数标签,请为该参数写下划线(_)而不是显式参数标签

static func subTractTwoNumbers(_: Double, _: Double) {
 //implementation
}

另外,你在最后写了一个额外的花括号。

答案 1 :(得分:0)

在扩展名中写入函数,如下所示

 extension MyExtension {


     func addTwoNumber(number1: Double, number2: Double) {
          //implementation
      }

        func subTractTwoNumbers(number1: Double, number2: Double) {
         //implementation
      }
        }