从类

时间:2015-10-26 11:31:52

标签: swift

我正努力使用功能变得自信。我正在练习下面的代码。

class Arithmetics {
var operand1: Double
var operand2: Double

init(operand1: Double, operand2: Double) {
    self.operand1 = operand1
    self.operand2 = operand2
    }    
func AddInsideClass(operand1: Double, operand2: Double) -> Double {
    var sum = operand1 + operand2
    return sum
    }
}

func AddOutsideClass(operand1: Double, operand2: Double) -> Double {
    var sum = operand1 + operand2
    return sum
    }

println(AddOutsideClass(5.5, 4.5))
println(Arithmetics.AddInsideClass(5.5, 4.5))

在最后两行中,我试图调用这些函数并在控制台上输出它们。第一个println()从类外调用函数,工作正常。 然而,第二个println()给出了一条错误消息,如下所示:

" stdin:23:35:错误:电话中的额外参数 println(Arithmetics.AddInsideClass(5.5,4.5)) ^ ~~~"

这里的问题是什么?

是不是因为我不能直接调用类方法?或者我只能通过类似下面的类实例调用类方法吗?

var operation1: Double = Arithmetics.AddInsideClass(5.5, 4.5)

2 个答案:

答案 0 :(得分:0)

  

类方法是一种对类对象而不是对象进行操作的方法   班级的实例。

AddInsideClass不是类方法。它只能使用类Arithmetics的对象调用,而不能使用类名本身调用。

创建类Arithmetics的对象,以便在另一个类中调用其方法。

let arithmeticsClassObj = Arithmetics()
println(arithmeticsClassObj.AddInsideClass(5.5, 4.5))

参考:Apple Docs

答案 1 :(得分:0)

您有两种选择:

首先 - 使用您的语法 - 您将该函数声明为静态,您可以省略变量和init函数

class Arithmetics {

  static func addInsideClass(operand1: Double, operand2: Double) -> Double {
    var sum = operand1 + operand2
    return sum
  }
}

您可以在课堂上调用它(第二个参数名称是必需的)

Arithmetics.addInsideClass(5.5, operand2:4.5)

第二次您创建了一个类的实例,该实例现在不需要add函数中的操作数,因为它们是在init函数中设置的。

class Arithmetics {
  var operand1: Double
  var operand2: Double

  init(operand1: Double, operand2: Double) {
    self.operand1 = operand1
    self.operand2 = operand2
    }

  func addInsideClass() -> Double {
    var sum = operand1 + operand2
    return sum
    }
}

调用它的语法是

let operation1 = Arithmetics(operand1: 5.5, operand2: 4.5)
operation1.addInsideClass()
相关问题