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

关键词:

用来声明的:

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

用于子句的:

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

表达式和类型的:

  1. as, dynamicType, is, new, super, self, __COLUMN__, __FILE__, __FUNCTION__, __LINE__

特殊语境使用的:

  1. didSet, get, inout, mutating, override, set, unowned, unowned(safe), unowned(unsafe), weak , willSet

class

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

如果定义一个汽车类

  1. class Car
  2. {
  3. init()
  4. {
  5. //to do init something.
  6. }
  7. }

init

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

deinit

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

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

enum

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

extension

扩展,有点像oc中的categories 。

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

如下面扩展字符串:

 
  1. extension String{
  2. struct _Dummy {
  3. var idxVal: Int
  4. var _padding: Int
  5. var _padding2: Int
  6. var _padding3: Int
  7. }
  8. //过虑出数字
  9. func fitlerCharater() -> String
  10. {
  11. var numberstr : String = ""
  12. for character in self
  13. {
  14. let s :String = String(character)
  15.  
  16. //println(s.toInt())
  17. if let hs = s.toInt()
  18. {
  19. numberstr += character
  20. }
  21. }
  22. return numberstr
  23. }
  24.  
  25. //扩展使用下标访问
  26. subscript (i: Int) -> Character {
  27. var dummy: _Dummy = reinterpretCast(i >= ? self.startIndex : self.endIndex)
  28. dummy.idxVal += i
  29. let idx: String.Index = reinterpretCast(dummy)
  30. return self[idx]
  31. }
  32.  
  33. //扩展使用Range访问
  34. subscript (subRange: Range<Int>) -> String {
  35. var start: _Dummy = reinterpretCast(self.startIndex)
  36. var end = start
  37. start.idxVal = subRange._startIndex
  38. end.idxVal = subRange._endIndex
  39. let startIndex: String.Index = reinterpretCast(start)
  40. let endIndex: String.Index = reinterpretCast(end)
  41. return self[startIndex..endIndex]
  42. }
  43. }

测试:

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

输出:

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

func

用来修饰函数的关键词。

import

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

let

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

var

用来声明变量。

protocol

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

static

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

struct

用来修饰结构体。

subscript

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

  1. class Garage
  2. {
  3. var products : String[] = Array()
  4.  
  5. subscript(index:Int) -> String
  6. {
  7. get
  8. {
  9. return products[index]
  10. }
  11.  
  12. set
  13. {
  14. if index < products.count //&& !products.isEmpty
  15. {
  16. products[index] = newValue
  17. }
  18. else
  19. {
  20. products.append(newValue)
  21. }
  22.  
  23. }
  24. }
  25. }

测试:

  1. func testSubscript()
  2. {
  3. var garage = Garage()
  4. garage[] = "A"
  5. garage[] = "B"
  6. garage[] = "C"
  7. garage[] = "D"
  8. garage[] = "CC"
  9.  
  10. println("index 1 = \(garage[0]) ,index 2 = \(garage[1]),index 3 = \(garage[2]) ,index 4 = \(garage[3])")
  11. }

输出

  1. index = A ,index = B,index = CC ,index = D

typealias

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

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

break

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

case

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

continue

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

default

缺省声明。常见在switch中。

do, else,if, for, return, switch, while

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

in

范围或集合操作

  1. let str = ""
  2. for c in str
  3. {
  4. println(c)
  5. }

fallthrough

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

  1. let integerToDescribe =
  2. var description = "The number \(integerToDescribe) is"
  3. switch integerToDescribe {
  4. case , , , , , , , :
  5. description += " a prime number, and also";
  6. fallthrough
  7. case :
  8. description += " an integer"
  9. default :
  10. description += " finished"
  11. }
  12.  
  13. println(description)

输出:

  1. The number is a prime number, and also an integer

where

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

  1. let yetAnotherPoint = (, -)
  2. switch yetAnotherPoint {
  3. case let (x, y) where x == y:
  4. println("(\(x), \(y)) is on the line x == y")
  5. case let (x, y) where x == -y:
  6. println("(\(x), \(y)) is on the line x == -y")
  7. case let (x, y):
  8. println("(\(x), \(y)) is just some arbitrary point")
  9. }
  10.  
  11. switch的条件满足where 后面的条件时,才执行语句。

is

as

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

  1. for view : AnyObject in self.view.subviews
  2. {
  3. if view is UIButton
  4. {
  5. let btn = view as UIButton;
  6. println(btn)
  7. }
  8. }

OC的写法:

  1. for (UIView *view in self.view.subviews)
  2. {
  3. if ([view isKindOfClass:[UIButton class]]) //is 操作
  4. {
  5. UIButton *btn =(UIButton *)view //as 操作
  6. }
  7. }

super

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

__COLUMN__, __FILE__, __FUNCTION__, __LINE__

是不是有点像宏定义啊。

  1. println(__COLUMN__ ,__FILE__, __FUNCTION__, __LINE__)

输出:

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

set,get

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

willSet,didSet

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

inout

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

  1. func swapTwoInts(inout a: Int, inout b: Int) {
  2. let temporaryA = a
  3. a = b
  4. b = temporaryA
  5. }

mutating

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

  1. protocol ExampleProtocol {
  2. var simpleDescription: String { get }
  3. mutating func adjust()
  4. }
  5.  
  6. class SimpleClass: ExampleProtocol {
  7. var simpleDescription: String = "A very simple class."
  8. func adjust() {
  9. simpleDescription += " Now 100% adjusted."
  10. }
  11. }
  12.  
  13. struct SimpleStructure: ExampleProtocol {
  14. var simpleDescription: String = "A simple structure"
  15. mutating func adjust() { //如果去除mutating 报Could not find an overload for '+=' that accepts the supplied arguments
  16. simpleDescription += " (adjusted)"
  17. }
  18. }
 

测试

父子类之间的函数重写,即复盖。

unowned, unowned(safe), unowned(unsafe)

无宿主引用。

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

weak

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

---

作者:fengsh998
原文地址:http://blog.csdn.net/fengsh998/article/details/32133809
转载请注明出处

Swift 07.关键字的更多相关文章

  1. Swift - mutating关键字的使用

    转载自:http://www.jianshu.com/p/14cc9d30770a  感谢作者:此ID想了很久 Swift中protocol的功能比OC中强大很多,不仅能再class中实现,同时也适用 ...

  2. Swift - defer关键字(推迟执行)

    在一些语言中,有try/finally这样的控制语句,比如Java. 这种语句可以让我们在finally代码块中执行必须要执行的代码,不管之前怎样的兴风作浪. 在Swift 2.0中,Apple提供了 ...

  3. Swift - final关键字的介绍,以及使用场景

    final关键字在大多数的编程语言中都存在,表示不允许对其修饰的内容进行继承或者重新操作.Swift中,final关键字可以在class.func和var前修饰. 通常大家都认为使用final可以更好 ...

  4. Swift之关键字使用(I)

    static和class的使用 static 使用 在非class的类型(包括enum和struct)中,一般使用static来描述类型作用域.在这个类型中,我们可以在类型范围中声明并使用存储属性,计 ...

  5. Swift 特殊关键字 与符号

    #available() 函数来检查API函数的可用性 // 判断当前版本是否 iOS8.0+,OSX10.10+以及以其他平台 if #available(iOS 8.0, OSX 10.10, * ...

  6. swift final关键字、?、!可选与非可选符

    ?符号: 可选型 在初始化时可以赋值为nil !符号:  隐形可选型 类型值不能为nil,如果解包后的可选类型为nil会报运行时错误,主要用在一个变量/常量在定义瞬间完成之后值一定会存在的情况.这主要 ...

  7. Swift的关键字

    在声明中使用关键字 let   :声明一个常量 var :声明一个变量 class :声明一个类 static :静态的 deinit :反初始化方法?析构方法 init :构造方法?初始化方法 en ...

  8. Swift - 07 - 布尔类型

    //: Playground - noun: a place where people can play import UIKit var str = "Hello, playground& ...

  9. Swift—final关键字-b

    在类的定义中使用final关键字声明类.属性.方法和下标.final声明的类不能被继承,final声明的属性.方法和下标不能被重写. 下面看一个示例: final class Person { //声 ...

随机推荐

  1. 《利用python进行数据分析》读书笔记--第四章 numpy基础:数组和矢量计算

    http://www.cnblogs.com/batteryhp/p/5000104.html 第四章 Numpy基础:数组和矢量计算 第一部分:numpy的ndarray:一种多维数组对象 实话说, ...

  2. js_保留关键字

    网页可以被我们分为三个大的部分:结构,表现,形式而js就是专对于表现的,js是一门编程的解释性脚本语言,和其他的语言相同js也有自己的保留的关键字,下面我们来看看js保留的关键字吧!js一共有56个关 ...

  3. 介绍MFSideMenu左右滑动控件的使用

    昨天刚写完侧滑菜单的实例,今天在CocoaChina网站上看到一篇非常好的侧滑菜单设计案例文章,分享给大家.http://www.cocoachina.com/macdev/uiue/2013/071 ...

  4. Android 软件盘 Editext 问题

    显示的问题:android:windowSoftInputMode="adjustPan|stateHidden" 弹出布局Editext并且挤上去 android:windowS ...

  5. ucos中的三种临界区管理机制

    熟悉ucos,或者读过Jean.J.Labrosse写过的ucos书籍的人,一定会知道ucos中著名的临界区管理宏:OS_ENTER_CRITICAL()和OS_EXIT_CRITICAL(). 同样 ...

  6. Oracle创建数据库

    Oracle创建数据库有三种方式:一.使用DBCA(Database Configuration Assistant 数据库配置助手):二.使用 create database指令:三.在安装数据库软 ...

  7. [linux] scp无密码拷贝

    源服务器为s,ip为111.111.111.112. 目标服务器为d, ip为111.111.111.111 1>在源服务器新建用户 test_s, useradd test_s -g user ...

  8. JAX-WS使用Handler Chain加工消息

    承前 本文的示例,是基于前一篇文章中的实例而改进的,如果想要运行本文的代码例子,需要先实现前一篇的代码. 前一篇文章JAX-WS开发WebService初级 Handler概念 在WebService ...

  9. 标准W3C盒子模型和IE盒子模型CSS布局经典盒子模型(转)

    盒子模型是css中一个重要的概念,理解了盒子模型才能更好的排版.其实盒子模型有两种,分别是 ie 盒子模型和标准 w3c 盒子模型.他们对盒子模型的解释各不相同,先来看看我们熟知的标准盒子模型: 从上 ...

  10. Web开发的发展历史

    了解一下Web开发相关的历史,相关技术的演进历程,知其前世今生,非常有助于加深Web开发相关技术的理解和认识. 下面是对网上几篇相关文章的总结和摘要: 1. Web开发的发展史 对过去的15年来,We ...