iOS开发——Swift篇&Swift关键字详细介绍
Swift关键字详细介绍
每一种语言都有相应的关键词,每个关键词都有他独特的作用,来看看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
用来定义一个类,相信大家并不陌生。
如果定义一个汽车类
- class Car
- {
- init()
- {
- //to do init something.
- }
- }
init
相对于类的构造方法的修饰。
deinit
相对于类的释构方法的修饰。
对于类的构造和释构在swift 中需要使用关键词来修饰,而很多高级语言并不需要特别的指定,便C++ 只需要类名与构造函数名相同就可以,不需要额外的关键词。
enum
枚举类型的声明,这个与很多语方都相通。
extension
扩展,有点像oc中的categories 。
Swift 中的可以扩展以下几个:
添加计算型属性和计算静态属性
定义实例方法和类型方法
提供新的构造器
定义下标
定义和使用新的嵌套类型
使一个已有类型符合某个接口
如下面扩展字符串:
- extension String{
- struct _Dummy {
- var idxVal: Int
- var _padding: Int
- var _padding2: Int
- var _padding3: Int
- }
- //过虑出数字
- func fitlerCharater() -> String
- {
- var numberstr : String = ""
- for character in self
- {
- let s :String = String(character)
- //println(s.toInt())
- if let hs = s.toInt()
- {
- numberstr += character
- }
- }
- return numberstr
- }
- //扩展使用下标访问
- subscript (i: Int) -> Character {
- var dummy: _Dummy = reinterpretCast(i >= 0 ? self.startIndex : self.endIndex)
- dummy.idxVal += i
- let idx: String.Index = reinterpretCast(dummy)
- return self[idx]
- }
- //扩展使用Range访问
- subscript (subRange: Range<Int>) -> String {
- var start: _Dummy = reinterpretCast(self.startIndex)
- var end = start
- start.idxVal = subRange._startIndex
- end.idxVal = subRange._endIndex
- let startIndex: String.Index = reinterpretCast(start)
- let endIndex: String.Index = reinterpretCast(end)
- return self[startIndex..endIndex]
- }
- }
测试:
- func testExtension()
- {
- var str : String = "1234ab5国6cd7中8i90"
- println(str.fitlerCharater())
- let china: String = "china operating system public to 世界"
- println("使用下标索引访问第13个字符 \(china[13])")
- println("使用负号下标即变为从右往左访问字符 \(china[-1])")
- println("使用负号下标即变为从右往左访问字符 \(china[-2])")
- println("使用下标Range来访问范围 \(china[2...6])")
- dump(china[1..5], name: "china[1:4]") //使用dump输出
- dump(china[10...13], name: "china[10:13]")
- }
输出:
- 1234567890
- 使用下标索引访问第13个字符 n
- 使用负号下标即变为从右往左访问字符 界
- 使用负号下标即变为从右往左访问字符 世
- 使用下标Range来访问范围 ina o
- - china[1:4]: hina
- - china[10:13]: atin
func
用来修饰函数的关键词。
import
导入头文件,相信大家都不陌生,但在swift 中好像被用来导入包,如import UIKit。 因为swift中没有了头文件的概念。
let
用来修改某一常量的关键词。像const 限定差不多
var
用来声明变量。
protocol
协议,也有称为接口,这个往往在很多高级语言中不能多重继承的情况下使用协议是一个比较好的多态方式。
static
用来修饰变量或函数为静态
struct
用来修饰结构体。
subscript
下标修饰,可以使类(class),结构体(struct),枚举(enum) 使用下标访问。
- class Garage
- {
- var products : String[] = Array()
- subscript(index:Int) -> String
- {
- get
- {
- return products[index]
- }
- set
- {
- if index < products.count //&& !products.isEmpty
- {
- products[index] = newValue
- }
- else
- {
- products.append(newValue)
- }
- }
- }
- }
测试:
- func testSubscript()
- {
- var garage = Garage()
- garage[0] = "A"
- garage[1] = "B"
- garage[2] = "C"
- garage[3] = "D"
- garage[2] = "CC"
- println("index 1 = \(garage[0]) ,index 2 = \(garage[1]),index 3 = \(garage[2]) ,index 4 = \(garage[3])")
- }
输出
- index 1 = A ,index 2 = B,index 3 = CC ,index 4 = 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
范围或集合操作
- let str = "123456"
- for c in str
- {
- println(c)
- }
fallthrough
由于swift中的switch语句中可以省去了break的写法,但在其它语言中省去break里,会继续往后一个case跑,直到碰到break或default才完成。在这里fallthrough就如同其它语言中忘记写break一样的功效。
- let integerToDescribe = 1
- var description = "The number \(integerToDescribe) is"
- switch integerToDescribe {
- case 1, 3, 5, 7, 11, 13, 17, 19:
- description += " a prime number, and also";
- fallthrough
- case 5:
- description += " an integer"
- default :
- description += " finished"
- }
- println(description)
输出:
- The number 1 is a prime number, and also an integer
where
swift中引入了where 来进行条件判断。
- let yetAnotherPoint = (1, -1)
- switch yetAnotherPoint {
- case let (x, y) where x == y:
- println("(\(x), \(y)) is on the line x == y")
- case let (x, y) where x == -y:
- println("(\(x), \(y)) is on the line x == -y")
- case let (x, y):
- println("(\(x), \(y)) is just some arbitrary point")
- }
当switch的条件满足where 后面的条件时,才执行语句。
is
as
is 常用于对某变量类型的判断,就像OC中 isKindClass ,as 就有点像强制类型转换的意思了。
- for view : AnyObject in self.view.subviews
- {
- if view is UIButton
- {
- let btn = view as UIButton;
- println(btn)
- }
- }
OC的写法:
- for (UIView *view in self.view.subviews)
- {
- if ([view isKindOfClass:[UIButton class]]) //is 操作
- {
- UIButton *btn =(UIButton *)view //as 操作
- }
- }
self:本身
Self、
Type:类型
super
基类的关键语,通常称父类
__COLUMN__, __FILE__, __FUNCTION__, __LINE__
是不是有点像宏定义啊。
- println(__COLUMN__ ,__FILE__, __FUNCTION__, __LINE__)
输出:
- (17, /Users/apple/Desktop/swiftDemo/swiftDemo/ViewController.swift, viewDidLoad(), 62)
associativity:运算符的结合性
set,get
常用于类属性的setter getter操作。
willSet,didSet
在swift中对set操作进行了扩展,willset 在set新值成功前发生,didset在设置新值成功后发生。
inout
对函数参数作为输出参数进行修饰。
- func swapTwoInts(inout a: Int, inout b: Int) {
- let temporaryA = a
- a = b
- b = temporaryA
- }
mutating
具体不是很理解,好像是专为结构体使用而设置的变体声明
- protocol ExampleProtocol {
- var simpleDescription: String { get }
- mutating func adjust()
- }
- class SimpleClass: ExampleProtocol {
- var simpleDescription: String = "A very simple class."
- func adjust() {
- simpleDescription += " Now 100% adjusted."
- }
- }
- struct SimpleStructure: ExampleProtocol {
- var simpleDescription: String = "A simple structure"
- mutating func adjust() { //如果去除mutating 报Could not find an overload for '+=' that accepts the supplied arguments
- simpleDescription += " (adjusted)"
- }
- }
测试
- func testMutating()
- {
- var a = SimpleClass()
- a.adjust()
- let aDescription = a.simpleDescription
- println(aDescription)
- var b = SimpleStructure()
- b.adjust()
- let bDescription = b.simpleDescription
- println(bDescription)
- }
override
父子类之间的函数重写,即复盖。
当标准的操作符不满足我们的要求时,就需要自定义一些操作符。
新的操作符需要用 operator 关键字声明在全局变量中,可以用 prefix,infix,postfix 声明
例如:
prefixoperator⋅ {}
现在我们定义一个新的操作符 ⋅ 使结构体 Vector2D 做向量相乘
- infix operator ⋅ {
- associativity none
- precedence 160
- }
infix
表示要定义的是一个中位操作符,即前后都是输入
associativity
定义了结合律,即如果多个同类的操作符顺序出现的计算顺序。比如常见的加法和减法都是 left,就是说多个加法同时出现时按照从左往右的顺序计算 (因为加法满足交换律,所以这个顺序无所谓,但是减法的话计算顺序就很重要了)。点乘的结果是一个 Double,不再会和其他点乘结合使用,所以这里写成 none;详见:这里
precedence
运算的优先级,越高的话优先进行计算。swift 中乘法和除法的优先级是 150 ,加法和减法的优先级是 140 ,这里我们定义点积的优先级为 160 ,就是说应该早于普通的乘除进行运算。
- func ⋅ (left: Vector2D, right: Vector2D) -> Double {
- return left.x * right.x + left.y * right.y
- }
unowned, unowned(safe), unowned(unsafe)
无宿主引用。
[unowned self] 或[unowned(safe) self] 或[unowned(unsafe) self]
weak
弱引用,使得对象不会被持续占有
iOS开发——Swift篇&Swift关键字详细介绍的更多相关文章
- iOS开发UI篇—UIScrollView控件介绍
iOS开发UI篇—UIScrollView控件介绍 一.知识点简单介绍 1.UIScrollView控件是什么? (1)移动设备的屏幕⼤大⼩小是极其有限的,因此直接展⽰示在⽤用户眼前的内容也相当有限 ...
- iOS开发UI篇—常见的项目文件介绍
iOS开发UI篇—常见的项目文件介绍 一.项目文件结构示意图 二.文件介绍 1.products文件夹:主要用于mac电脑开发的可执行文件,ios开发用不到这个文件 2.frameworks文件夹主要 ...
- iOS开发多线程篇 09 —NSOperation简单介绍
iOS开发多线程篇—NSOperation简单介绍 一.NSOperation简介 1.简单说明 NSOperation的作⽤:配合使用NSOperation和NSOperationQueue也能实现 ...
- iOS开发——实战篇Swift篇&UItableView结合网络请求,多线程,数据解析,MVC实战
UItableView结合网络请求,多线程,数据解析,MVC实战 学了这么久的swift都没有做过什么东西,今天就以自己的一个小小的联系,讲一下,怎么使用swift在实战中应用MVC,并且结合后面的高 ...
- iOS开发——OC篇&常用关键字的使用与区别
copy,assign,strong,retain,weak,readonly,readwrite,nonatomic,atomic,unsafe_unretained的使用与区别 最近在学习iOS的 ...
- iOS开发——UI篇Swift篇&玩转UItableView(一)基本使用
UItableView基本使用 class ListViewController: UIViewController , UITableViewDataSource, UITableViewDeleg ...
- iOS开发——设备篇Swift篇&判断设备类型
判断设备类型 1,分割视图控制器(UISplitViewController) 在iPhone应用中,使用导航控制器由上一层界面进入下一层界面. 但iPad屏幕较大,通常使用SplitViewCo ...
- iOS开发——实用篇Swift篇&项目开发常用实用技术
项目开发常用实用技术 实现拨打电话 要实现打电话功能,最简单最直接的方式便是:直接跳到拨号界面 (注意:这个需要真机调试,模拟器无效果) UIApplication.sharedApplica ...
- iOS开发——动画篇Swift篇&动画效果的实现
Swift - 动画效果的实现 在iOS中,实现动画有两种方法.一个是统一的animateWithDuration,另一个是组合出现的beginAnimations和commitAnimation ...
- iOS开发——语法篇&swift经典语法总结
swift经典语法总结 1:函数 1.1 func funcNmae()->(){} 这样就定义了一个函数,它的参数为空,返回值为空,如果有参数和返回值直接写在两个括号里就可以了 1.2 参数需 ...
随机推荐
- 【转】tomcat下jndi的三种配置方式
jndi(Java Naming and Directory Interface,Java命名和目录接口)是一组在Java应用中访问命名和目录服务的API.命名服务将名称和对象联系起来,使得我们可以用 ...
- (四)学习JavaScript之className属性
参考:http://www.w3school.com.cn/jsref/prop_classname.asp HTML DOM Anchor 对象 定义和用法 className 属性设置或返回元素的 ...
- spring exception--No unique bean of type
今天碰到一个问题,就是我现有项目需要加一个定时器任务,我的代码如下: <!-- 每日数据同步 总数监测任务******************begin --> <bean id=& ...
- docker专题(2):docker常用管理命令(上)
http://segmentfault.com/a/1190000000751601 本文只记录docker命令在大部分情境下的使用,如果想了解每一个选项的细节,请参考官方文档,这里只作为自己以后的备 ...
- poj2686-Traveling by Stagecoach(状压dp)
题意: n张马票,m个城市,马票上有马数(决定速度),一张只能用一次,给出地图,求从城市a到b的最短时间. 分析:n值很小状态压缩 #include <map> #include < ...
- HDU4614 Vases and Flowers 二分+线段树
分析:感觉一看就是二分+线段树,没啥好想的,唯一注意,当开始摆花时,注意和最多能放的比大小 #include<iostream> #include<cmath> #includ ...
- windows内核窥探
windows是一个非常优秀的OS,从今天开始,我要和大家共同分享windows给我们带来的快乐!本人只所以将自己的学习笔记与大家分享,一是让自己更深入的理解windows,再就是有什么疏漏之处,望大 ...
- cocos2d-x在NDK r9下的编译问题
:69: error: format not a string literal andno format arguments [-Werror=format-security]cc1plus.exe: ...
- POJ 1005 解题报告
1.题目描述 2.解题思路 好吧,这是个水题,我的目的暂时是把poj第一页刷之,所以水题也写写吧,这个题简单数学常识而已,给定坐标(x,y),易知当圆心为(0,0)时,半圆面积为0.5*PI*(x ...
- 在生成 Visual c + + 2005年或从 DLL 文件中使用 CString 派生的类的 Visual c + +.net 应用程序时,您可能会收到 LNK2019 错误消息
http://support.microsoft.com/kb/309801