作者:fengsh998
原文地址:http://blog.csdn.net/fengsh998/article/details/28258805
转载请注明出处
如果觉得文章对你有所帮助,请通过留言或关注微信公众帐号fengsh998来支持我,谢谢!

3号,端午刚过,回到公司第一个早上的两小时便贡献给了apple的ios 8 发布会,在看完后,感觉操作系统越来越离我们的生活更近了,更多的应用支持了人们的日常生活,健康,娱乐,旅游等领域,相信以后的生活也更加人工智能化,在发布会的最后,提到了swift的全新开发语言,据发布会上的介绍,更新安全,快捷,编码高效。因此也对此进行了第一阶段的初探与学习。

语言语法笔记:

1.常量和变量的定义。

常量使用let 进行约束, 变量使用var来约束,相信大家对var并不陌生,如早期的VB, pascal,js等都会有这样的定义。但根据书中介绍,swift对常量,和变量的约束,编译更加精确,有时候用户可以不需要声明某个常量是什么类型,像通常 声明一个变量 int  b = 0; 而 在swift中使用var b=0 即可,swift可根据初始化的值进行判断是变量是什么类型,如果var 中没有指定足够的信息(当然是机算判断变量类型的信息时,)可以使用分号进行加以说明,如书中的例子:

let implicitInteger = 70             //会自动识别为integer
let implicitDouble = 70.0
let explicitDouble: Double = 70    //加上类型说明

变量的声明与使用

var myVariable = 42
myVariable = 50
var explicitVariable:Double = 60

还有一点有意思是变量或常量的命名名称,几呼支持各种字符,包知unicode字符。

[cpp] view plaincopy
  1. let constvalue = 70 ;let 我爱你中国 = "我要写中国的操作系统" ;println(constvalue) ;println(我爱你中国);

上面代码写在一行时,需要用分隔号分开,如果不使用分号,可以使用换行符:

[cpp] view plaincopy
  1. let constvalue = 70
  2. let 我爱你中国 = "我要写中国的操作系统"
  3. println(constvalue)
  4. println(我爱你中国)

运行后输出:

[html] view plaincopy
  1. 70
  2. 我要写中国的操作系统

2.字符串串接及类型转换

大家可能用OC都有一个想骂人的串接问题,如 在nsstring *a = "hello" 串接 " world",常常使用stringbyappendstring ,或使用stringWithFormat:"%@,%@" 来串接,有没有?而不能使用"+"操作符。真难过,实在难过,特别是对于C/C++,PASCAL,JAVA 甚至更多高级语言都是支持“+”号操作符。唯有OC特别,搞得我一个同事说,想学习一下IOS,但语言太另类了,其实啥语言都大差不差,习惯就好。现在好了,swift来了,他也支持“+”号操作符了。如:

“let label = "The width is "
let width = 94
let widthLabel = label + String(width)”

同时大家也可能发现了,width是整型,在这里被显式的强制类型转换为字符型,这里有个疑问,就是 如果没有进行强制类型转换,这let widthLabel = label +  width这样是否可以编译过呢?编译器会不会隐式的进行转换呢,我也好期待,因为没有操作环境,只是在看swift官方学习文档中的,因此留在这里,后续有环境进行验证一下。

接下来说说这个类型转换,咋看又像在抄pascal 或java 的语法, c/c++ 的风格的都是(类型)变量,如(char *) var ,(double) var,而不会写成double(var),oc的写法,与c/C++的很像。没太搞明白为毛,即整合c/c++的,又特地搞个风格别致的,当然,什么都不要紧,习惯就好。对吧,大伙说。

不过swift似呼也嗅到了什么,也提提供了另一种参变量使用"\()" 操作符,其中括号中的还支持表达式操作。至于反斜扛操作嘛,就有点像大家在C/C++  中的换行串接时,在行尾加上的\的含议差不多。看一下官方给出的例子:

“let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit.”

可能用文字表达不出\()的意思,其实就是参数变量 把上面四句翻译为oc 则为 
NSInteger apples = 3;

NSInteger oranges = 5;

NSString *appleSummary = [NSString stringWithFormat:@"I have %d apples",apples];

经试验:

[cpp] view plaincopy
  1. let constvalue = 70
  2. let 我爱你中国 = "我要写中国的操作系统"
  3. let ok = String(constvalue)+我爱你中国
  4. let okgood = "字符串串接\(我爱你中国)"
  5. println(okgood)

输出为:

字符串串接我要写中国的操作系统

数据类型别名:

oc /c/c++都使用typedef 来约束新的类型别名

而swift 则使用typealias

typealias AudioSample = UInt16

字符串常量可以包括下面这些特殊字符:
空字符\0,反斜杠\,制表符\t,换行符\n,回车符\r,双引号\”和单引号\’
单字节Unicode字符,\xnn,其中nn是两个十六进制数
双字节Unicode字符,\unnnn,其中nnnn是四个十六进制数
四字节Unicode字符,\Unnnnnnnn,其中nnnnnnnn是八个十六进制数

[cpp] view plaincopy
  1. let wiseWords = "\"Imagination is more important than knowledge\" - Einstein"
  2. // "Imagination is more important than knowledge" - Einstein
  3. let dollarSign = "\x24" // $, Unicode scalar U+0024
  4. let blackHeart = "\u2665" // ♥, Unicode scalar U+2665
  5. let sparklingHeart = "\U0001F496" // , Unicode scalar U+1F496

初始化一个空字串

[cpp] view plaincopy
  1. var emptyString = "" // empty string literal
  2. var anotherEmptyString = String() // initializer syntax

同时可以使用isEmpty来判断字符串是否为空,这点真的很像pascal,delphi就是这样检测的。

[cpp] view plaincopy
  1. if emptyString.isEmpty {
  2. println("Nothing to see here")
  3. }

在swift中字符串不是指针,而是实际的值,因此,在Swift中,一个String类型就是一个实际的值,当定义一个新的String,并且将之前的String值拷贝过来的时候,是实际创建了一个相等的新值,而不是仅仅像指针那样指向过去。同样在函数传递参数的时候,也是传递的实际值,并且创建了一个新的字符串, 后续的操作都不会改变原有的String字符串 。
单个字符的声明,像c/c++中使用 char ,而swift中则使用:

[cpp] view plaincopy
  1. let yenSign: Character = "¥"

通过for-in循环,可以遍历字符串中的每一个字符

[cpp] view plaincopy
  1. for character in "Dog!" {
  2. println(character)
  3. }


字符串长度的统计,可以使用全局函数countElements可以计算一个字符串中字符的数量,这点与其它语言length好像有点不同。

[cpp] view plaincopy
  1. let unusualMenagerie = "Koala , Snail , Penguin , Dromedary "
  2. println("unusualMenagerie has \(countElements(unusualMenagerie)) characters")
  3. // prints "unusualMenagerie has 40 characters"

字符串与单个字符,可以使用+,+=操作将字符串和字符串接在一起。这点与其它语言稍先进一点。

字符串的比较使用 ==

[cpp] view plaincopy
  1. let quotation = "We're a lot alike, you and I."
  2. let sameQuotation = "We're a lot alike, you and I."
  3. if quotation == sameQuotation {
  4. println("These two strings are considered equal")
  5. }
  6. // prints "These two strings are considered equal"
  7. //输出”These two strings are considered equal”

swift还保留了oc中的前后缀函数hasPrefix和hasSuffix

大小写字符串使用uppercaseString 和 lowercaseString

unicode :

Swift 支持多种不同的方式取得Unicode字符串.
你可以使用for-in语句遍历字符串,来获得每一个字符的Unicode编码值。这个过程已经在字符(Working with Characters)描述过了。
或者,下面三个描述中使用合适的一个来获得一个字符串的值
UTF-8字符编码单元集合使用String类型的utf-8属性
UTF-16字符编码单元集合使用String类型的utf-16属性
21位Unicode标量集合使用String类型的unicodeScalars属性

如例子:

[cpp] view plaincopy
  1. let testUncode = "Dog!狗"
  2. for codeUnit in testUncode.utf8 {
  3. print("\(codeUnit) ")
  4. }
  5. print("\n")
  6. // 68 111 103 33 231 139 151
  7. for codeUnit in testUncode.utf16 {
  8. print("\(codeUnit) ")
  9. }
  10. print("\n")
  11. // 68 111 103 33 29399
  12. for scalar in testUncode.unicodeScalars {
  13. print("\(scalar.value) ")
  14. }
  15. print("\n")
  16. // 68 111 103 33 29399

在utf-8中,中文的"狗"占三个字节,而在utf-16 及标量(utf-32)中正好可以一个字节就装得下。


3.数组,字典

在swift的书中说,数组和字典都使用“[]”中括符,并可以通过索引或KEY /VALUE的方式存储。见官方例子:

“var shoppingList = ["catfish", "water", "tulips", "blue paint"]     //声明一个四元素的数组变量
shoppingList[1] = "bottle of water" //重新将元素2的进行赋值
 
var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations”    //动太的添加一个jayne的key值为Public Relations

这个k/V的数组是否长的有点像JOSN啊。反正我看像,还可以动太的添加哦,

创建一个空的数组如: let   emptyArray = String[]() //又是中括号又是圆括符的,看得真让人眼花。不过swift中说了,如果不需要指字类型,则数组可以直接使用"[ ]"

进行。如: shoppingList = []   ,字典则使用 “ [ :]” 来设为空字典。

另外字典增加了一个定议模式,有点像C++中的vector 或map之类的,可以指字 k/v的类型吧。见例:

“let emptyDictionary = Dictionary<String, Float>()”

整体感觉上还是比较像C++吧。

[cpp] view plaincopy
  1. //数组使用
  2. //初始化时指定长度 确定类型的
  3. var threeDoubles = Double[](count: 3, repeatedValue: 0.0)
  4. println(threeDoubles)
  5. //不确定类型的
  6. var anotherThreeDoubles = Array(count: 3, repeatedValue: 2.5)
  7. println(anotherThreeDoubles)
  8. //var computerList = String[]() //创建一个空的数组
  9. var computerList: String[] = ["lenovo", "dell"]
  10. //var computerList = ["lenovo", "dell"] //与上等效
  11. if !computerList.isEmpty //判断是否为空数组
  12. {
  13. //数组长度
  14. println("数组共有 \(computerList.count) 元素.")
  15. println("元素分别为 \(computerList.description)") //使用description访问
  16. }
  17. //直接置空
  18. computerList = []
  19. println("空数组 \(computerList)")
  20. //动态追加元素
  21. computerList.append("sony")
  22. println("追加后为:\(computerList)")           //真接访问
  23. computerList += "acer"
  24. println("追加后为:\(computerList.description)")
  25. //可以一次追加一个数组
  26. computerList += ["HP", "samsung", "Apple"]
  27. println("追加数组后为:\(computerList)")
  28. var items = ["Haier","东之"]
  29. computerList += items
  30. println("追加数组后为:\(computerList)")
  31. //下标访问
  32. println("你访问索引3的元素\(computerList[3])")
  33. //使用下标进行修改元素值
  34. println("修改前为:\(computerList[2])")
  35. computerList[2]="SONY"
  36. println("修改后为:\(computerList[2])")
  37. //通过闭包访问一次修改多个值
  38. //注意[4..6]是半闭包即只包括改修4,5而不包括6
  39. //使用[4...6]是全闭包,可以修改4,5,6
  40. computerList[4...6] = ["惠普", "三星","a","b","c"]//元素超出部分会直接追加在末尾
  41. println("修改后为:\(computerList)")
  42. //插入元素
  43. computerList.insert("computer", atIndex: 0)
  44. println("插入后为:\(computerList)")
  45. //通过索引进行删除元素
  46. let del = computerList.removeAtIndex(0)
  47. println("删除的元素为:\(del)")
  48. //移除最后一个元素
  49. let dellast = computerList.removeLast()
  50. println("最后的元素为:\(dellast)")
  51. //遍历数组
  52. for item in computerList
  53. {
  54. println(item)
  55. }
  56. //如果需要每一个元素的整形的索引值,使用enumerate函数代替会更方便
  57. //enumerate函数对于每一个元素都会返回一个包含元素的索引和值的元组
  58. for (index, value) in enumerate(computerList)
  59. {
  60. println("Item \(index + 1): \(value)")
  61. }

字典的使用

[cpp] view plaincopy
  1. //字典
  2. //Dictionary<KeyType,ValueType> 唯一的限制就是KeyType必须是可哈希的(hashable)
  3. //var namesOfIntegers = Dictionary<Int, String>()  //创建空字典
  4. var airport :Dictionary<String, String> = ["TYO": "Tokyo", "DUB": "Dublin"]
  5. var airports = ["TYO": "Tokyo", "DUB": "Dublin"]
  6. //字典元素
  7. println("字典包函元素有 \(airports.count) ")
  8. //使用key添加 value
  9. airports["LHR"] = "London"
  10. println("添加元素后\(airports)")
  11. //使用key修改
  12. airports["LHR"] = "London Heathrow"
  13. println("修改元素后\(airports)")
  14. /*updateValue(forKey:) 方法如果键不存在则会设置它的值,如果键存在则会更新它的值, 和下标不一样是
  15. updateValue(forKey:) 方法 如果更新时,会返回原来旧的值rThis enables you to 可以使用这个来判断是否发生了
  16. updateValue(forKey:) 方法返回一个和字典的值相同类型的可选值. 例如,
  17. 如果字典的值的类型时String,则会返回String? 或者叫“可选String“,
  18. 这个可选值包含一个如果值发生更新的旧值和如果值不存在的nil值。
  19. */
  20. if let oldValue = airports.updateValue("Dublin International", forKey: "DUB")
  21. {
  22. println("The old value for DUB was \(oldValue).")
  23. println("最新值\(airports)")
  24. }
  25. //判空
  26. if let airportName = airports["DUB"]
  27. {
  28. println("The name of the airport is \(airportName).")
  29. }
  30. else
  31. {
  32. println("That airport is not in the airports dictionary.")
  33. }
  34. //字典移除
  35. airports["APL"] = "Apple International"
  36. println("当前字典:\(airports)")
  37. airports["APL"] = nil
  38. println("移除后字典:\(airports)")
  39. //也可以使用removeValueForKey 移除
  40. if let removedValue = airports.removeValueForKey("DUB")
  41. {
  42. println("The removed airport's name is \(removedValue).")
  43. }
  44. else
  45. {
  46. println("The airports dictionary does not contain a value for DUB.")
  47. }
  48. //遍历字典
  49. for (airportCode, airportName) in airports
  50. {
  51. println("\(airportCode): \(airportName)")
  52. }
  53. //遍历key
  54. for airportCode in airports.keys
  55. {
  56. println("Airport code: \(airportCode)")
  57. }
  58. //遍历value
  59. for airportName in airports.values
  60. {
  61. println("Airport name: \(airportName)")
  62. }
  63. //获取所有key 转为数组
  64. let airportCodes = Array(airports.keys)
  65. println("所有keys 为:\(airportCodes)")
  66. //获取所有value 转为数组
  67. let airportNames = Array(airports.values)
  68. println("所有values 为:\(airportNames)")

4.枚举类型

枚举在swift中可胃得到了很高的提升。不单单只简单的支持Int数据类型,还扩展了支持其它数据类型,一起来探究一下吧

基本语法:

[cpp] view plaincopy
  1. enum CompassPoint {
  2. case North
  3. case South
  4. case East
  5. case West
  6. }

每个case 为一个成员,但多个成员也可以写在一个case里,用逗号分隔

[cpp] view plaincopy
  1. enum Planet {
  2. case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
  3. }

声明及使用

[cpp] view plaincopy
  1. //一旦指定了类型就可以使用.操作
  2. var dicection : CompassPoint
  3. dicection = .East
  4. var directionToHead = CompassPoint.West
  5. directionToHead = .South

与 switch配合使用

[cpp] view plaincopy
  1. var directionToHead = CompassPoint.West
  2. switch directionToHead {
  3. case .North:
  4. println("Lots of planets have a north")
  5. case .South:
  6. println("Watch out for penguins")
  7. case .East:
  8. println("Where the sun rises")
  9. case .West:
  10. println("Where the skies are blue")
  11. //        default:  //如果不需要各个都配置时,可以使用defult
  12. //            println("no what");
  13. }

枚举的关联值支持

Swift的枚举类型可以由一些数据类型相关的组成,如果需要的话,这些数据类型可以是各不相同的。枚举的这种特性跟其它语言中的奇异集合
如:

[cpp] view plaincopy
  1. enum Barcode {
  2. case UPCA(Int, Int, Int)
  3. case QRCode(String)
  4. }

然后可以使用任何一种类型来创建如:

[cpp] view plaincopy
  1. var productBarcode = Barcode.UPCA(8, 85909_51226, 3)

此示例创建一个名为productBarcode新的变量,并与相关联的元组值赋给它Barcode.UPCA的值(8,8590951226,3)。
也可以使用:

[cpp] view plaincopy
  1. productBarcode = .QRCode("ABCDEFGHIJKLMNOP")

不同的条码类型像以前一样可以使用一个switch语句来检查,但是这一次相关的值可以被提取作为switch语句的一部分。您提取每个相关值作为常数(let前缀)或变量(var前缀)不同的情况下,在switch语句的case代码内使用

[cpp] view plaincopy
  1. switch productBarcode {
  2. case .UPCA(let numberSystem, let identifier, let check):
  3. println("UPC-A with value of \(numberSystem), \(identifier), \(check).")
  4. case .QRCode(let productCode):
  5. println("QR code with value of \(productCode).")
  6. }

如果所有的枚举成员的关联值的提取为常数,或者当所有被提取为变量,为了简洁起见,可以放置一个var,或let标注在成员名称前

[cpp] view plaincopy
  1. switch productBarcode {
  2. case let .UPCA(numberSystem, identifier, check):
  3. println("UPC-A with value of \(numberSystem), \(identifier), \(check).")
  4. case let .QRCode(productCode):
  5. println("QR code with value of \(productCode).")
  6. }

别外也可以有给成员设置指定值:

[cpp] view plaincopy
  1. enum ASCIIControlCharacter: Character {
  2. case Tab = "\t"               //这里设置值要与<span style="font-family: Arial, Helvetica, sans-serif;">Character 类型相对应</span>
  3. case LineFeed = "\n"
  4. case CarriageReturn = "\r"
  5. }
[cpp] view plaincopy
  1. enum ASCIIControlCharacter: Int {
  2. case Tab = 10
  3. case LineFeed = 20
  4. case CarriageReturn = 30
  5. }

同样还可以使枚举跟c/C++,java,pascal phyon等高级语言的效果一样。只需要设置第一个值后,后面的值会类推。

[cpp] view plaincopy
  1. enum Planet: Int {
  2. case Mercury = 1, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune
  3. }

后面的成员会自增。
同时swift还提供了访问枚举成中中的原始值,使用toRaw()如:

[cpp] view plaincopy
  1. let earthsOrder = Planet.Earth.toRaw()
  2. // earthsOrder is 3

另外,还提供了一个检查访问,fromRaw()

[cpp] view plaincopy
  1. let possiblePlanet = Planet.fromRaw(7)
  2. // possiblePlanet is of type Planet? and equals Planet.Uranus

使用枚举的fromRaw方法来试图找到一个特定的原始值枚举成员。这个例子识别Uranus的位置通过原始值为7:然而,并非所有可能的Int值都会找到一个匹配的星球。正因如此,该fromRaw方法返回一个可选的枚举成员。在上面的例子中,是possiblePlanet类型Planet?或“可选的Planet”。
如果你试图找到一个Planet为9的位置,通过fromRaw返回可选的Planet值将是无:因此在配合switch时可以这样:

[cpp] view plaincopy
  1. let positionToFind = 9
  2. if let somePlanet = Planet.fromRaw(positionToFind) {
  3. switch somePlanet {
  4. case .Earth:
  5. println("Mostly harmless")
  6. default:
  7. println("Not a safe place for humans")
  8. }
  9. } else {
  10. println("There isn't a planet at position \(positionToFind)")
  11. }
  12. // prints "There isn't a planet at position 9"

5.条件表达式。

if/swicth

“let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
    if score > 50 {
        teamScore += 3
    } else {
        teamScore += 1
    }
}”
teamScore

为什么都不加括号了?对于多个表达式,还是这样长蛇阵么?

另外书中有这一段“In an if statement, the conditional must be a Boolean expression—this means that code such as if score { ... } is an error, not an implicit comparison to zero.”
个人理解是,如果在一个条件语句中,条件值必须是BOOL表达式的,因为非BOOL表达式不会隐式的与0进行比较,这点可能与传统的if有点不同吧。

经验证:多个条件也不需要用括号的。不过,如果你想要表达式正确,还是要按照运算优先级。

[cpp] view plaincopy
  1. var constvalueB = 200
  2. let constvalue = 70
  3. if constvalueB == 0 && constvalue > 60 || constvalue != 20
  4. {
  5. println("true")
  6. }
  7. else
  8. {
  9. println("false")
  10. }

别外像:

[cpp] view plaincopy
  1. var constvalueB = 200
  2. let constvalue = 70
  3. if constvalueB
  4. {
  5. println("true")
  6. }
  7. else
  8. {
  9. println("false")
  10. }

[cpp] view plaincopy
  1. constvalueB

这样的条件,在swift中已经通不过了,对条件判断也更别严格了。

再来看一下switch,这个总算有点点进步了,以前的switch大多只支持int或枚举类型,现在swift中把switch语句的表达式判断类型上进行了扩展。其次,每个case不再需要写break;这点不错。

“let vegetable = "red pepper"
switch vegetable {
case "celery":
    let vegetableComment = "Add some raisins and make ants on a log."
case "cucumber", "watercress":
    let vegetableComment = "That would make a good tea sandwich."
case let x where x.hasSuffix("pepper"):
    let vegetableComment = "Is it a spicy \(x)?"
default:
    let vegetableComment = "Everything tastes good in soup."
}”

哈哈,看到没有,没有break哦。。。冒似少了几个B的代码。

switch语句的case中可以匹配一个数值范围

[cpp] view plaincopy
  1. let count = 3_000_000_000_000
  2. let countedThings = "stars in the Milky Way"
  3. var naturalCount: String
  4. switch count {
  5. case 0:
  6. naturalCount = "no"
  7. case 1...3:
  8. naturalCount = "a few"
  9. case 4...9:
  10. naturalCount = "several"
  11. case 10...99:
  12. naturalCount = "tens of"
  13. case 100...999:
  14. naturalCount = "hundreds of"
  15. case 1000...999_999:
  16. naturalCount = "thousands of"
  17. default:
  18. naturalCount = "millions and millions of"
  19. }
  20. println("There are \(naturalCount) \(countedThings).")

case中还可以直接测试元组是否符合相应的条件,_可以匹配任意值

[cpp] view plaincopy
  1. let somePoint = (1, 1)
  2. switch somePoint {
  3. case (0, 0):
  4. println("(0, 0) is at the origin")
  5. case (_, 0):
  6. println("(\(somePoint.0), 0) is on the x-axis")
  7. case (0, _):
  8. println("(0, \(somePoint.1)) is on the y-axis")
  9. case (-2...2, -2...2):
  10. println("(\(somePoint.0), \(somePoint.1)) is inside the box")
  11. default:
  12. println("(\(somePoint.0), \(somePoint.1)) is outside of the box")
  13. }
  14. // prints "(1, 1) is inside the box"

在case匹配的同时,可以将switch语句中的值绑定给一个特定的常量或者变量,以便在case的语句中使用。比如

[cpp] view plaincopy
  1. let anotherPoint = (2, 0)
  2. switch anotherPoint {
  3. case (let x, 0):
  4. println("on the x-axis with an x value of \(x)")
  5. case (0, let y):
  6. println("on the y-axis with a y value of \(y)")
  7. case let (x, y):
  8. println("somewhere else at (\(x), \(y))")
  9. }
  10. // prints "on the x-axis with an x value of 2"

思考:如果没有defalut:会是什么样的?有环境验证一下。

验证后有几个有意思的地方:

一,对成员具有完整性检测:如:

[cpp] view plaincopy
  1. enum CompassPoint :Int {
  2. case North
  3. case South
  4. case East
  5. case West
  6. }
  7. var directionToHead = CompassPoint.West   //预先指定为West
  8. switch directionToHead {
  9. case .North:
  10. println("Lots of planets have a north")
  11. case .South:
  12. println("Watch out for penguins")
  13. case .East:
  14. println("Where the sun rises")
  15. }

这里编译期会报错,提示未找到West。
可以通过以下两种方式进行修正:

[cpp] view plaincopy
  1. switch directionToHead {
  2. case .North:
  3. println("Lots of planets have a north")
  4. case .South:
  5. println("Watch out for penguins")
  6. case .East:
  7. println("Where the sun rises")
  8. case .West:
  9. println("Where the west");
  10. }
[cpp] view plaincopy
  1. switch directionToHead {
  2. case .North:
  3. println("Lots of planets have a north")
  4. case .South:
  5. println("Watch out for penguins")
  6. case .East:
  7. println("Where the sun rises")
  8. default:
  9. println("Where the west");
  10. }

别外还遇到一个告警问题:

如果switch的条件声明在同一个函数内,这时会提示Switch condition evaluates to a constant
要去除这个,只需要将声明的变量放在函数外就可以

var directionToHead : CompassPoint = .West

6.循环

for - in,for, while, do-while

在for-in  中使用k/v数组,

“let interestingNumbers = [
    "Prime": [2, 3, 5, 7, 11, 13],
    "Fibonacci": [1, 1, 2, 3, 5, 8],
    "Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
largest”

这个让我感慨的就是每个变量都没有进行显式的声明类型。这也许就是swift所宣存的精确,高效的一个原因之一吧。

另外for 也像pascal一样支持“..”范围操作符。可能熟释DELPHI的朋友一定很深的印象。像这样的for

procedure foroperation

var

char c;

begin

for (c in ['a'..'z']) do

begin

//do something.

end;

end;

官网的例子:

“var firstForLoop = 0
for i in 0..3 {
    firstForLoop += i
}
firstForLoop
 
var secondForLoop = 0
for var i = 0; i < 3; ++i {
    secondForLoop += 1
}
secondForLoop”

两个for 过程是一样的,即i都是从0-3. 其实delphi 中还有low() to high()操作的,这个swift应该没有吧,如果有的话,我想apple的工程师都应经历了pascal的时代。

值得注意的是:swift中不仅有".." 也有"...",分别代表什么呢。两个点,相当于小于如0..3 等价于 0<=i<3 而使用...则相等于 "<=" 如  0..3 等价于 0<=i<=3

while / do while

“var n = 2
while n < 100 {
    n = n * 2
}
n
 
var m = 2
do {
    m = m * 2
} while m < 100
m”

7.函数的语法

“func greet(name: String, day: String) -> String {
    return "Hello \(name), today is \(day)."
}
greet("Bob", "Tuesday")”

通过这个例子,可以看到使用func关键词进行声明,其次 输入参数 使用“变量:类型”的型式,这还真像pascal,你还别说。最有特色的就是这个返回值,参过->符号指定返回的类型。这个也许是C++的地址函问符的一个使用方式吧,每个函数返回的其实都是一个地址块。另外函数如果有多个返回(即传出参数)怎么处理呢?如C/C++ 的使用“**”指针的指针 如 func(char ** outstring)  但在 swift中则:

“func getGasPrices() -> (Double, Double, Double) {
    return (3.59, 3.69, 3.79)
}
getGasPrices()”

其次swift中的函数参数为数组时的写法,也很特别:

“func sumOf(numbers: Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}
sumOf()
sumOf(42, 597, 12)”

内连函数的支持

很多高级语方中都有内连函数,内连函数的使用也是很常见的一种,不仅使得代码执行更加高效,同时也减少了内存碎片。

一起看一下swift的内连函数的写法:

“func returnFifteen() -> Int {
    var y = 10
    func add() {
        y += 5
    }
    add()
    return y
}
returnFifteen()”

还有一个特另的:就是swift还提供了在函数中返回函数来看一下,写法也比较另类:

“func makeIncrementer() -> (Int -> Int) {
    func addOne(number: Int) -> Int {
        return 1 + number
    }
    return addOne
}
var increment = makeIncrementer()     //increment 可理解为addOne的函数指针
increment(7)”

把这段代码解读一下,首先红色部分是一个函数,入参为整型,返回一个整型的值。 再来看最外层的函数makeIncrementer 没有入参,有返回值,而返回值是使用"()"括起来。

int ->int  这个表示返回的为一个函数地址,该函数有一个int型的输入参数,同时还有一个int 型的返回值参数。这与c/c++的函数指很是有差别。

在swift中,函数也可以作为参数进行传递:(见红色部分)

“func hasAnyMatches(list: Int[], condition: Int -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}
func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]
hasAnyMatches(numbers, lessThanTen)”

最后还有三个没有理解透,等有ios 8 的环境再验证,好像是匿名函数的使用。

“numbers.map({
    (number: Int) -> Int in
    let result = 3 * number
    return result
    })”

“numbers.map({ number in 3 * number })”

“sort([1, 5, 3, 12, 2]) { $0 > $1 }”

写得有点粗,英文不怎么样,边看,边理解,边记录的。

好吧,今天就先学到到这,希望这个对你有所帮助。别还不知道是否为大小写敏感的,若是的话,还真有点蛋痛,看他的官方例子,某些关键词一会大写开头,一会小写开头。。。。。。。下一个学习,将是swift的对象和类(即面向对象编程)

初探swift语言的学习笔记一(基本数据类型)相关推荐

  1. 初探swift语言的学习笔记九(OC与Swift混编)

    作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/34440159 转载请注明出处 如果觉得文章对你有所帮助,请通过留言 ...

  2. 初探swift语言的学习笔记四(类对象,函数)

    2019独角兽企业重金招聘Python工程师标准>>> swift扩展了很多功能和属性,有些也比较奇P.只有慢慢学习,通过经验慢慢总结了. 下面将初步学习一下类的写法. 码工,最大爱 ...

  3. 初探swift语言的学习笔记十(block)

    作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/35783341 转载请注明出处 如果觉得文章对你有所帮助,请通过留言 ...

  4. 初探swift语言的学习笔记八(保留了许多OC的实现)

    作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/32715833 转载请注明出处 如果觉得文章对你有所帮助,请通过留言 ...

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

    作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/32133809 转载请注明出处 如果觉得文章对你有所帮助,请通过留言 ...

  6. 初探swift语言的学习笔记五(线程)

    作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/30354127 转载请注明出处 假设认为文章对你有所帮助,请通过留言 ...

  7. 初探swift语言的学习笔记十一(performSelector)

    作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/35842441 转载请注明出处 如果觉得文章对你有所帮助,请通过留言 ...

  8. 初探swift语言的学习笔记六(ARC-自动引用计数,内存管理)

    作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/31824179 转载请注明出处 如果觉得文章对你有所帮助,请通过留言 ...

  9. 初探swift语言的学习笔记三(闭包-匿名函数)

    作者:fengsh998 原文地址:http://blog.csdn.net/fengsh998/article/details/29353019 转载请注明出处 如果觉得文章对你有所帮助,请通过留言 ...

最新文章

  1. 华为手机如何升级鸿蒙系统_能运行EMUI 11才能升级到鸿蒙2.0,只有这些手机能升级,有你的吗...
  2. git bash退回上一个文件夹
  3. 2018-2019-1 20165330 《信息安全系统设计基础》第二周学习总结
  4. mysql addslashes_PHP函数addslashes和mysql_real_escape_string的区别
  5. 天池 在线编程 输入流
  6. CentOS中VMware tools的安装以及安装失败的解决办法,java架构师视频课程
  7. ChaiNext:市场热情仍在,也需留意高位风险
  8. 如何修复GitKraken Inotify Limit Error\idea erro - 升级Ubuntu / Linux inotify限制
  9. centos7连接华为san存储_centos7配置nfs共享存储服务
  10. 小区的净水设备,应该很少人用,为什么
  11. java对谷歌不兼容_谷歌浏览器不兼容的一些Js
  12. 吊销 BTChina 营业执照”后元旦之前可能相继落马的“影视下载”网站名单
  13. mcinabox运行库下载_MCinaBox运行库
  14. 每日一诗词 —— 临江仙·滚滚长江东逝水
  15. 防骗数据库,查询骗子电话QQ等
  16. 欧拉筛法筛素数(接近O(n),取模操作稍微慢一点) 4E7之内的素数 Apare_xzc
  17. IO流,小白入门基础知识
  18. Java微信公众平台开发之OAuth2.0网页授权
  19. 静态网页之--小说阅读网
  20. kuka机器人焊接编程入门教程_焊接机器人操作编程与应用教学.pptx

热门文章

  1. 列表逆序排序_Python零基础入门学习05:容器数据类型:列表和元组
  2. 文件流导出乱码_Savespss:不使用StatTransfer也可转换dta为sav文件的利器
  3. 知乎回答多线程爬虫案例
  4. 期末复习、化学反应工程科目(第一章)
  5. 三十九、Java集合中的HashSet和TreeSet
  6. pytorch 实现线性回归
  7. 论NLP可解释的评估:什么才是“好”的解释?
  8. 限时免费 | 人工智能项目实战训练营,给你一个成为AI算法工程师的机会
  9. ICCV 2019开源论文 | 捕捉图像DNA——单幅图像下可实现任意尺度自然变换
  10. 本周最热 AI 论文大集合,还不快一键收藏?