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

前端技术 2023/09/07 IOS

方法
在 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的值方法. 实例方法以 \".\" 语法访问

局部和外部参数名称
Swift 函数描述了局部和全局变量声明。同样,Swift 方法的命名规则也类似 Objective C。但是局部和全局参数名称声明的特性对于函数和方法不同。 swift 第一个参数是由介词名称\'with\', \'for\' 和 \'by\' 访问命名规则。

Swift 提供声明作为局数参数名称,其它参数名称为全局参数名,第一参数是方法名称。在这里,“no1”方法作为局部参数名来声明。 \'no2\' 用于全局声明,并通过该程序访问。

复制代码 代码如下:

class division {var count:Int=0
    func incrementBy(no1:Int, no2:Int){
        count = no1 / no2
        println(count)}}let counter = division()
counter.incrementBy(1800, no2:3)
counter.incrementBy(1600, no2:5)
counter.incrementBy(11000, no2:3)

当我们使用 playground 运行上面的程序,得到以下结果

600
320
3666

外部参数名称使用 # 和 _ 符号
尽管 Swift 方法提供第一个参数名称作为局部声明,用户必须提供以修改参数名称从局部到全局声明。这可以通过\'#\'符号前缀使用第一参数名来完成。通过这样做,第一参数可以作为全局在整个模块访问。

当用户需要使用外部名称访问在后面的参数名中,方法的名字使用“_”符号覆盖。

复制代码 代码如下:

class multiplication {var count:Int=0
    func incrementBy(#no1:Int, no2:Int){
        count = no1 * no2
        println(count)}}let counter = multiplication()
counter.incrementBy(no1:800, no2:3)
counter.incrementBy(no1:100, no2:5)
counter.incrementBy(no1:15000, no2:3)

当我们使用 playground 运行上面的程序,得到以下结果

2400
500
45000

在方法中的Self属性
方法有一个隐式属性被称为“self”,所有定义的类型实例所都有。“self”属性被用于表示当前的实例定义的方法。

复制代码 代码如下:

class calculations {let a:Intlet b:Intlet res:Int
   
    init(a:Int, b:Int){self.a = a
        self.b = b
        res = a + b
        println(\"Inside Self Block: \\(res)\")}
   
    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)let sum = calculations(a:1200, b:300)

pri.result()
sum.result()

本文地址:https://www.stayed.cn/item/18070

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。