在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
本篇是Swift内部培训整理的PPT材料,主要内容来源于苹果Swift编程语言官方教程,参考了网上的一些视频课程内容。在教程介绍完之后,本人附带实现了一个项目开发中的常用场景的Demo:基于导航栏和Tab栏的应用。 1.Swift概述 我们先来看一篇文章:《苹果新贵 Swift之前世今生》 Swift是用于设计iOS及Mac OS X应用的一门新语言。 1.1.Swift特点
1.2.Swift代码的文件扩展名 *.swift 2.第一个Swift程序 2.1.使用Xcode Project编写 2.2.使用Playground编写 我们可以基于 Playground 做这些事情:
3.常量与变量 let关键词声明常量,var关键词声明变量。 let maximumNumberOfLoginAttempts = 10 // 常量只有在初始化的时候可以赋值 var currentLoginAttempt = 0 4.运算符和表达式 4.1.运算符
4.2.表达式 1.不指定数据类型 var a1 = 10 var a2 = 20 var a = a1 > a2 ? "a1":"a2" 2.指定数据类型 var a1:Int = 10 var a2:Int = 20 var a = a1 > a2 ? "a1":"a2" 3.可以有分号结尾 var a1:Int = 10; var a2:Int = 20 var a = a1 > a2 ? "a1":"a2" 4.3.注释 // /* */ 5.数据类型 5.1.整型 Swift提供8、16、32、64位形式的有符号及无符号整数,这些整数类型遵循C语言的命名规约。与Swift中的所有类型一样,这些整数类型的名称以大写字母开头。 Swift还提供了一个整数类型Int;
Swift还提供了无符号整数类型UInt。 5.2.浮点型
5.3.数字型 表示数字如下: let decimalInteger = 17 // 表示是10进制 let binaryInteger = 0b10001 // 二进制17 let octalInteger = 0o21 // 8进制17 let hexadecimalInteger = 0x11 // 16进制17 5.4.布尔类型 true和false let orangesAreOrange = true let turnipsAreDelicious = false 6.数据类型转换 6.1.整型转换 不同类型的整数常量或变量所能存储的值域不同,需要显示地转换 let twoThousand:UInt16 = 2000 let one:UInt8 = 1 //let twoThousandAndOne = twoThousand + one // 错误 let twoThousandAndOne = twoThousand + UInt16(one) // 正确 6.2.整型与浮点数转换 整数与浮点数类型之间的转换,需要显示地转换: let three = 3 let pointOneFourOneFiveNine = 0.14159 let pi = Double(three) + pointOneFourOneFiveNine 7.字符串类型 7.1.字符串初始化 1.初始化 let someString = "Some string literal value" let wiseWords = "\"Imagination is more important than knowledge\" - Einstein" let dollarSign = "\x24" // $,Unicode scalar U+0024 2.空值 var emptyString = "" // 空串初始化 var anotherEmptyString = String() // 通过初始化函数初始化 3.空值判断 if emptyString.isEmpty{ println("Nothing to see here") } if emptyString == ""{ println("Nothing to see here") } 7.2.字符串修改 var 声明的可以修改,let不能修改。 var variableString = "Horse" variableString += " and carriage" 7.3.字符串插入 斜杠+括号+变量 let multiplier = 3 let message = "\(multiplier) times 2.5 is \(Double(multiplier) * 2.5)" 7.4.字符串长度 使用countElements函数。OC中使用length属性。 let unusualMenagerie = "Koala , Snail, Penguin" println("unusualMenagerie has \(countElements(unusualMenagerie)) characters") 7.5.比较字符串相等 let quotation = "We're a lot alike,you and I." let sameQuotation = "We're a lot alike,you and I." if quotation == sameQuotation{ println("These two strings are considered equal") } 8.元组(tuple)类型 元组将多个值组合为单个值。元组内的值可以是任意类型,各元素不必是相同的类型,元组在作为函数返回值时尤其有用。 1.定义方法1 let http404Error = (404,"Not Found") println("The status code is \(http404Error.0)"); println("The status message is \(http404Error.1)"); 2.定义方法2 let http200Error = (statusCode:404,discription:"Not Found") println("The status code is \(http200Error.statusCode)"); println("The status message is \(http200Error.discription)"); 9.可选(Optional)类型 9.1.使用可选类型 我们在如下情况下使用可选类型:
let possibleNumber = "123" let convertedNumber:Int?=possibleNumber.toInt() “Int?”是可选类型 if convertedNumber{ println("\(possibleNumber) has an Integer value of \(convertedNumber!)") } else{ println("\(possibleNumber) could not be convented to an integer") } convertedNumber是从可选类型中取值 9.2.使用nil 我们可以为可选类型的变量设置nil值,表示没有任何值。 var serverResponseCode:Int?=404 serverResponseCode = nil 如果不是可选类型,那么是不能设置为nil的 10.数组 10.1.数组初始化 基本语法: [value1,value2,value3] var shoppingList:String[] = [“Eggs","Milk"] 对比一下OC中的方式: NSArray *array = @[@"aa",@"bb"]; 10.2.数组追加元素 使用append函数追加或通过+操作符: var shoppingList:String[] = ["Eggs","Milk"] shoppingList.append("Flour") shoppingList += ["Cheese","Butter"] 10.3.数组插入元素 使用insert方法: var shoppingList:String[] = ["Eggs","Milk"] shoppingList.insert("Butter", atIndex: 0) shoppingList += ["Cheese","Chocolate Spread"] 比较一下OC中: [array insertObject:@"dd" atIndex:1]; 10.4.数组删除元素 使用removeAtIndex方法 var shoppingList:String[] = ["Eggs","Milk","Butter"] let deleteItem = shoppingList.removeAtIndex(2) println(deleteItem) println(shoppingList) 10.5.数组长度 使用count属性(和OC中一样): var shoppingList:String[] = ["Eggs","Milk","Butter"] println("The shopping list contains \(shoppingList.count) items.") 10.6.数组遍历 1.遍历方法1 var shoppingList:String[] = ["Eggs","Milk","Butter"] for item in shoppingList{ println(item) } 2.遍历方法2 有循环变量: for(index,value) in enumerate(shoppingList){ println("Item \(index + 1):\(value)") } 11.字典 11.1.字典初始化 基本语法: [key1:value1,key2:value2,key3:value3] var airports:Dictionary<String,String> = ["TYO":"Tokyo","DUB":"Dublin"] 11.2.字典追加元素 var airports:Dictionary<String,String> = ["TYO":"Tokyo","DUB":"Dublin"] airports["LHR"] = "Lonton" println("The dictionary of airports contains \(airports.count)") 11.3.字典删除元素 通过removeValueForKey(key)方法删除 var airports:Dictionary<String,String> = ["TYO":"Tokyo","DUB":"Dublin"] if let removedValue = airports.removeValueForKey("DUB"){ println("The removed airport's name is \(removedValue)") } else{ println("The airports dictionary does not contains a value for DUB") } 11.4.字典长度 使用count属性 println("The count of airport's is \(airports.count)") 11.5.字典遍历 1.遍历字典 var airports:Dictionary<String,String> = ["TYO":"Tokyo","DUB":"Dublin"] for (airportCode,airportName) in airports{ println("\(airportCode):\(airportName)") } 2.遍历键和值 for airportCode in airports.keys{ println("Airport code:\(airportCode)") } for airportName in airports.values{ println("Airport name\(airportName)") } 3.获得键和值的数组 let airportCodes = Array(airports.keys)
let airportNames = Array(airports.values)
12.控制语句 12.1.分支语句 1.条件语句if-else if boolean-expression{ statement1; }[else if boolean-expression{ statement2; }] [else{ statement3; }] 2.多分支语句switch switch some value to consider{ case value1,value2,value3: respond to value1 default: otherwise } 每个case不需要显示地添加break,每个case至少有一条语句。可以比较任何类型。 12.2.循环语句 1.while语句 while condition{ statements } 示例: var i = 100 var r = 0 var s = 0 var t = 0 while i < 1000 { r = i / 100 ; s = (i - r * 100) / 10; t = i - r * 100 - s * 10; if(i == r * r * r + s * s * s + t * t * t){ println("i=\(i)"); } i++ } 2.do-while语句 do{ statements }while condition 示例: var i = 100 var r = 0 var s = 0 var t = 0 do{ r = i / 100 ; s = (i - r * 100) / 10; t = i - r * 100 - s * 10; if(i == r * r * r + s * s * s + t * t * t){ println("i=\(i)"); } i++ }while i < 1000 3.for语句 for initialization;condition;increment{ statements } 示例: var i = 8 var r = 0 var s = 0 for var j = 0;j <= i;j++ { r = j * j; s = j * j * j; println("\(j)的平方:\(r) \(j)的立方:\(s)"); } 4.for in语句 一般用于遍历集合 1.遍历范围 for index in 1...5{ println("\(index) times 5 is \(index * 5)"); } 2.忽略循环变量 let base = 3 let power = 10 var answer = 1 for _ in 1...power{ answer *= base; } println("\(base) to the power of \(power) is \(answer)") 3.遍历数组 let names = ["Anna","Alex","Jack"] for name in names{ println("Hello,\(name)") } 4.遍历字典 let numberofLegs = ["spider":8,"ant":6,"car":4]; for(animalName,legCount) in numberofLegs{ println("\(animalName) have \(legCount) legs") } 5.遍历字符串 for character in "Hello"{ println(character) } 12.3.跳转语句
let integerDescribe = 5 var description = "The number \(integerDescribe) is" switch integerDescribe{ case 2,3,5: description += " a prise number,and also" fallthrough default: description += " an integer."; }
4.return 13.函数 13.1.函数定义 使用func定义一个函数。调用函数使用它的名字加上小括号中的参数列表。使用->分隔参数的名字和返回值类型。 函数声明: func greet(name:String,day:String) -> String{ return "Hello \(name),today is \(day)" } 函数调用: greet("Bob", "Tuesday") 13.2.无返回值函数 func sayGoodBye(personName:String){ println("Goodbye,\(personName)"); } sayGoodBye("Tony"); 13.3.多返回值函数 使用元组类型返回多个值 func count(string:String) -> (vowels:Int,consonants:Int,others:Int){ var vowel = 0,consonant = 0,other = 0; for character in string{ switch String(character).lowercaseString{ case "a","e","i","o","u": ++vowel; case "b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z": ++consonant; default: ++other; } } return (vowel,consonant,other); } let total = count("Some thing is change!"); println("\(total.vowels)元音,\(total.consonants)辅音") 13.4.嵌入函数 func chooseStepFunction(backwards:Bool) -> (Int) -> Int{ func stepForward(input:Int) -> Int{ return input + 1 } func stepBackward(input:Int) -> Int{ return input - 1 } return backwards ? stepBackward : stepForward } var currentValue = -4 // moveNearerToZero是一个函数指针 let moveNearerToZero = chooseStepFunction(currentValue > 0) while currentValue != 0{ println("\(currentValue)......") currentValue = moveNearerToZero(currentValue) } 14.闭包(Closure) 语法: {(parameters) -> return type in statements } 示例:数组排序 采用函数实现: let names = ["Chris","Alex","Ewa","Barry","Daniella" |
请发表评论