加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

初探swift语言的学习笔记七(swift 的关健词)

发布时间:2020-12-14 01:50:24 所属栏目:百科 来源:网络整理
导读:作者:fengsh998 原文地址: http://blog.csdn.net/fengsh998/article/details/32133809 转载请注明出处 如果觉得文章对你有所帮助,请通过留言或关注微信公众帐号 fengsh998 来支持我,谢谢! 每一种语言都有相应的关键词,每个关键词都有他独特的作用,来
作者:fengsh998
原文地址:http://blog.csdn.net/fengsh998/article/details/32133809
转载请注明出处
如果觉得文章对你有所帮助,请通过留言或关注微信公众帐号fengsh998来支持我,谢谢!


每一种语言都有相应的关键词,每个关键词都有他独特的作用,来看看swfit中的关键词:

关键词:

用来声明的:

“ class,deinit,enum,extension,func,import,init,let,protocol,static,struct,subscript,typealias,var.”

用于子句的:

“ break,case,continue,default,do,else,fallthrough,if,in,for,return,switch,where,while.”

表达式和类型的:

“ as,dynamicType,is,new,super,self,__COLUMN__,__FILE__,__FUNCTION__,__LINE__”

//特殊语境使用的:

“didSet,get,inout,mutating,override,set,unowned,unowned(safe),unowned(unsafe),weak,willSet”


class

用来定义一个类,相信大家并不陌生。

如果定义一个汽车类

[cpp] view plain copy
  1. classCar
  2. {
  3. init()
  4. //todoinitsomething.
  5. }
  6. }

init

相对于类的构造方法的修饰。


deinit

相对于类的释构方法的修饰。

对于类的构造和释构在swift 中需要使用关键词来修饰,而很多高级语言并不需要特别的指定,便C++ 只需要类名与构造函数名相同就可以,不需要额外的关键词。


enum

枚举类型的声明,这个与很多语方都相通。


extension

扩展,有点像oc中的categories 。

Swift 中的可以扩展以下几个:
添加计算型属性和计算静态属性
定义实例方法和类型方法
提供新的构造器
定义下标
定义和使用新的嵌套类型
使一个已有类型符合某个接口


如下面扩展字符串:

    extensionString{
  1. struct_Dummy{
  2. varidxVal:Int
  3. var_padding:Int
  4. var_padding2:Int
  5. var_padding3:Int
  6. }
  7. //过虑出数字
  8. funcfitlerCharater()->String
  9. varnumberstr:String=""
  10. forcharacterinself
  11. {
  12. lets:String=String(character)
  13. //println(s.toInt())
  14. ifleths=s.toInt()
  15. numberstr+=character
  16. returnnumberstr
  17. //扩展使用下标访问
  18. subscript(i:Int)->Character{
  19. vardummy:_Dummy=reinterpretCast(i>=0?self.startIndex:self.endIndex)
  20. dummy.idxVal+=i
  21. letidx:String.Index=reinterpretCast(dummy)
  22. returnself[idx]
  23. //扩展使用Range访问
  24. subscript(subRange:Range<Int>)->String{
  25. varstart:_Dummy=reinterpretCast(self.startIndex)
  26. varend=start
  27. start.idxVal=subRange._startIndex
  28. end.idxVal=subRange._endIndex
  29. letstartIndex:String.Index=reinterpretCast(start)
  30. letendIndex:String.Index=reinterpretCast(end)
  31. returnself[startIndex..endIndex]
  32. }

测试:

    functestExtension()
  1. varstr:String="1234ab5国6cd7中8i90"
  2. println(str.fitlerCharater())
  3. letchina:String="chinaoperatingsystempublicto世界"
  4. println("使用下标索引访问第13个字符(china[13])")
  5. println("使用负号下标即变为从右往左访问字符(china[-1])")
  6. println("使用负号下标即变为从右往左访问字符(china[-2])")
  7. println("使用下标Range来访问范围(china[2...6])")
  8. dump(china[1..5],name:"china[1:4]")//使用dump输出
  9. dump(china[10...13],name:"china[10:13]")
  10. }

输出:

    1234567890
  1. 使用下标索引访问第13个字符n
  2. 使用负号下标即变为从右往左访问字符界
  3. 使用负号下标即变为从右往左访问字符世
  4. 使用下标Range来访问范围inao
  5. -china[1:4]:hina
  6. -china[10:13]:atin

func

用来修饰函数的关键词。

import

导入头文件,相信大家都不陌生,但在swift 中好像被用来导入包,如import UIKit。 因为swift中没有了头文件的概念。

let

用来修改某一常量的关键词。像const 限定差不多

var

用来声明变量。

protocol

协议,也有称为接口,这个往往在很多高级语言中不能多重继承的情况下使用协议是一个比较好的多态方式。

static

用来修饰变量或函数为静态

struct

用来修饰结构体。

subscript

下标修饰,可以使类(class),结构体(struct),枚举(enum) 使用下标访问。

    classGarage
  1. varproducts:String[]=Array()
  2. subscript(index:Int)->String
  3. get
  4. returnproducts[index]
  5. set
  6. ifindex<products.count//&&!products.isEmpty
  7. products[index]=newValue
  8. else
  9. products.append(newValue)
    1. functestSubscript()
    2. vargarage=Garage()
    3. garage[0]="A"
    4. garage[1]="B"
    5. garage[2]="C"
    6. garage[3]="D"
    7. garage[2]="CC"
    8. println("index1=(garage[0]),index2=(garage[1]),index3=(garage[2]),index4=(garage[3])")
    9. }

    输出

      index1=A,index2=B,index3=CC,index4=D

    typealias

    类型别名,就像typedef一样。借typedef unsigned long int UInt64

    同样在swift中也可能自定义类型。


    break

    跳出循环,通常用于for,while,do-while,switch

    case

    case相信大家并不陌生,常在switch中使用,但如今在swift中多了一个地方使用哪就是枚举类型。

    continue

    跳过本次循环,继续往后执行。

    default

    缺省声明。常见在switch中。

    do,while

    这几个就不用多说了,越说越混。

    in

    范围或集合操作

      letstr="123456"
    1. forcinstr
    2. println(c)
    3. }

    fallthrough

    由于swift中的switch语句中可以省去了break的写法,但在其它语言中省去break里,会继续往后一个case跑,直到碰到break或default才完成。在这里fallthrough就如同其它语言中忘记写break一样的功效。

      letintegerToDescribe=1
    1. vardescription="Thenumber(integerToDescribe)is"
    2. switchintegerToDescribe{
    3. case1,3,5,7,11,13,17,19:
    4. description+="aprimenumber,andalso";
    5. fallthrough
    6. case5:
    7. description+="aninteger"
    8. default:
    9. description+="finished"
    10. println(description)

    输出:

      Thenumber1isaprimenumber,andalsoaninteger

    where

    swift中引入了where 来进行条件判断。

      letyetAnotherPoint=(1,-1)
    1. switchyetAnotherPoint{
    2. caselet(x,y)wherex==y:
    3. println("((x),(y))isonthelinex==y")
    4. )
    5. )
    6. }

    当switch的条件满足where 后面的条件时,才执行语句。

    is

    as

    is 常用于对某变量类型的判断,就像OC中 isKindClass ,as 就有点像强制类型转换的意思了。

      forview:AnyObjectinself.view.subviews
    1. ifviewisUIButton
    2. letbtn=viewasUIButton;
    3. println(btn)
    4. }

    OC的写法:

      for(UIView*viewinself.view.subviews)
    1. if([viewisKindOfClass:[UIButtonclass]])//is操作
    2. UIButton*btn=(UIButton*)view//as操作
    3. }

    super

    基类的关键语,通常称父类

    __COLUMN__,__LINE__

    是不是有点像宏定义啊。

      println(__COLUMN__,__LINE__)

    输出:

      (17,/Users/apple/Desktop/swiftDemo/swiftDemo/ViewController.swift,viewDidLoad(),62)

    set,get

    常用于类属性的setter getter操作。

    willSet,didSet

    在swift中对set操作进行了扩展,willset 在set新值成功前发生,didset在设置新值成功后发生。

    inout

    对函数参数作为输出参数进行修饰。

      funcswapTwoInts(inouta:Int,inoutb:Int){
    1. lettemporaryA=a
    2. a=b
    3. b=temporaryA
    4. }

    mutating

    具体不是很理解,好像是专为结构体使用而设置的变体声明

      protocolExampleProtocol{
    1. varsimpleDescription:String{get}
    2. mutatingfuncadjust()
    3. classSimpleClass:ExampleProtocol{
    4. varsimpleDescription:String="Averysimpleclass."
    5. funcadjust(){
    6. simpleDescription+="Now100%adjusted."
    7. structSimpleStructure:ExampleProtocol{
    8. varsimpleDescription:String="Asimplestructure"
    9. mutatingfuncadjust(){//如果去除mutating报Couldnotfindanoverloadfor'+='thatacceptsthesuppliedarguments
    10. simpleDescription+="(adjusted)"
    11. }
    测试
      functestMutating()
    1. vara=SimpleClass()
    2. a.adjust()
    3. letaDescription=a.simpleDescription
    4. println(aDescription)
    5. varb=SimpleStructure()
    6. b.adjust()
    7. letbDescription=b.simpleDescription
    8. println(bDescription)
    9. }
    override
    父子类之间的函数重写,即复盖。

    unowned,unowned(unsafe)

    无宿主引用。

    [unowned self] 或[unowned(safe) self] 或[unowned(unsafe) self]


    weak

    弱引用,使得对象不会被持续占有

    (编辑:李大同)

    【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读