这是方法还是功能?

时间:2017-03-30 18:20:13

标签: swift function methods

在假设getDataPoint()是一个方法而不是在此上下文中使用的函数时,我是否正确?

class Globals: NSObject{
   static let sharedInstance = Globals()

   func getDataPoint() -> Int {
      var theValue: Int
      //Some JSON code here
      return theValue
   }
}

class GameScene: SKScene{
   override func didMove(to: view: SKView){
      let globals = Globals.sharedInstance()

      var x = globals.getDataPoint() //Is a method?
   }
}

但如果我在Globals类中使用,我会称之为函数。

 class Globals: NSObject{
   static let sharedInstance = Globals()

   func foo() {
      print(\(getDataPoint())) //Is a function?
   }

   func getDataPoint() -> Int {
      var theValue: Int
      //Some JSON code here
      return theValue
   }
}

2 个答案:

答案 0 :(得分:2)

方法不是“与功能相对”,所以问题毫无意义。方法一个函数 - 在类型声明的顶层声明的函数。

func function() {}
class Class {
    func method() {}
    func anotherMethod() {
        func function() { }
    }
}

答案 1 :(得分:0)

这是一种方法。这只是Swift在没有cURL限定符的情况下引用方法和属性的简写的假象。

self.

与写作完全相同

func foo() {
   print(\(getDataPoint()))
}