详解Swift编程中的方法与属性的概念

2020-01-08 22:33:09丽君
易采站长站为您分析Swift编程中的方法与属性的概念,是Swift入门学习中的基础知识,需要的朋友可以参考下  

方法
在 Swift 中特定类型的相关联功能被称为方法。在 Objective C 中类是用来定义方法,其中作为 Swift 语言为用户提供了灵活性,类,结构和枚举中可以定义使用方法。

实例方法
在 Swift 语言,类,结构和枚举实例通过实例方法访问。

  • 实例方法提供的功能
  • 访问和修改实例属性
  • 函数关联实例的需要

    实例方法可以写在花括号 {} 内。它隐含的访问方法和类实例的属性。当该类型指定具体实例它调用获得访问该特定实例。

    语法

    复制代码
    func funcname(Parameters)-> returntype
    {Statement1Statement2---Statement N
        return parameters
    }
    示例
    复制代码
    class calculations {let a:Intlet b:Intlet res:Int
        
        init(a:Int, b:Int){self.a = a
            self.b = b
            res = a + b
        }
        
        func tot(c:Int)->Int{return res - c
        }
        
        func result(){
            println("Result is: (tot(20))")
            println("Result is: (tot(50))")}}let pri = calculations(a:600, b:300)
    pri.result()
    当我们使用 playground 运行上面的程序,得到以下结果

     

    
    Result is: 880
    Result is: 850
    

    Calculations 类定义了两个实例方法:

    init() 被定义为两个数 a 和 b 相加,并将其结果存储在'res'

    tot() 用于通过从 “res” 值减去 'c'

    最后,调用打印的计算a和b的值方法. 实例方法以 "." 语法访问