02-switch
//: Playground - noun: a place where people can play
importUIKit
varstr ="Hello, playground"
/* 1.不需要加break
* 2.必须穷举所有的可能性
*/
//判定字符串所在分支
letrating ="A"// String
switchrating{
case"a","A":
print("Great!")
case"b","B":
print("Just so so")
case"c","C":
print("it's not good")
case"d","D":
print("it's bad")
default:
print("Error!")
}
// switch语句和区间运算符结合
vargrade =93
switchgrade{
case90...100:
print("Grade is A")
case80..<90:
print("Grade is B")
case70...79:
print("Grade is C")
case60...69:
print("Grade is D")
default:
print("Unknown Grade")
}
// switch语句和元组的结合
letvector = (1,1)
switchvector{
//在x轴的正轴上(正值, 0)
case(1,0):
print("it an unit vector on the positive x-axis")
case(-1,0):
print("it an unit vector on the negative x-axis")
case(0,1):
print("it an unit vector on the positive y-axis")
case(0, -1):
print("it an unit vector on the negative y-axis")
default:
print("it is normal point")
}
// value binding:值绑定:使用临时的常量/变量获取元组(或者其他类型)的值
varvectorTwo = (10,0)
switchvectorTwo{
case(0,0):
print("it is origin")
case(letx,0)://只要y=0
print("This is x-axis")
print("x value is\(x)")
case(0,lety)://只要x=0
print("This is y-axis")
print("x value is\(y)")
default:
print("This is normal point")
}
//判断是在y=x还是在y=-x直线上;
varvectorThree = (10,10)
switchvectorThree{
// where模式匹配
caselet(x, y)wherex == y:
print("it's on the line y=x")
print("x value is\(x)")
caselet(x, y)wherex == -y:
print("it's on the line y=-x")
default:
print("This is normal point")
}
03-collection
//: Playground - noun: a place where people can play
importUIKit
varstr ="Hello, playground"
/* 1.初始化;
* 2.增/删/改/查
* 3.可变: var;不可变: let
*/
//数组(类型必须相同)
vararray = [1,2,3,4]
vararrayWithString: [String] = ["A","E","I","O","U"]
//创建空的可变数组(元素的个数为0)
vararrayOne:[Int] = []
vararrayTwo = [Int]()
vararrayThree:Array = []
vararrayFour =Array()
//查
arrayWithString[0]
arrayWithString.first
arrayWithString[0...4]
//添加
arrayWithString.append("hello")
arrayWithString+= ["Swift","Java"]
//func insert(newElement: Element, atIndex i: Int){}
arrayWithString.insert("OC", atIndex:5)
//删除
arrayWithString.removeFirst()
//修改
arrayWithString[5] ="Objective-C"
arrayWithString[0...2] = ["Ruby","Python","Perl"]
arrayWithString
//字典: key+value
//显示/隐式;
varcountries = ["US":"United States","IN":"India","CN":"Republic of China"]
//var countriesTwo: [String, String] = []
varcountriesThree:Dictionary = ["UK":"United Kingdom"]
//查
countries["CN"]
countries["AA"]
//改(不存在的key意味着添加)
countries["FR"] ="France"
countries["CN"] ="China"
//删
countries["US"] =nil
//集合:显示声明;去重复
varskillsOfPersion:Set = ["Swift","Java","JavaScript"]
varstringSet =Set(["one","two","three"])
//插入
skillsOfPersion.insert("Java")
skillsOfPersion
//删除
skillsOfPersion.removeFirst()
skillsOfPersion
//选择:集合(交集/并集....)/数组
04-optional
//: Playground - noun: a place where people can play
importUIKit
varstr ="Hello, playground"
//将字符串转成整型
letpossibleNumber ="hello"
letconvertedNumber =Int(possibleNumber)
varerrorCodeTwo:Int=500
//errorCodeTwo = nil
// **nil不能赋值给任何类型,除了可选型
//自定义整型可选型,和字符串可选型
varerrorCode:Int? =404// nil
varerrorMessage:String? ="Not Found"
//获取可选型的值(不能为nil的时候)
print("error message is\(errorMessage)")
//可选型解包(Unwrap):获取可选型存在的值(不能为nil的时候)
//方式一:强制解包;语法:!
//风险:当前的可选型必须有值
print("error message is\(errorMessage!)")
//方式二(C语言风格;不推荐):通过判断的方式进行解包
iferrorMessage!=nil{
print("error message is\(errorMessage!)")
}else{
print("No Error")
}
//方式三(推荐Swifty风格): optional binding(可选型绑定)->if let解包;和方式二结构等价
ifletunwrappedMsg =errorMessage{
print("error message is\(unwrappedMsg)")
}else{
print("No Error")
}
//使用同一个变量名字
ifleterrorMessage =errorMessage{
print("error message is\(errorMessage)")
}else{
print("No Error")
}
varnewString ="hello"
newString.rangeOfString("lm")
//如何使用if let对多个可选型解包
//var errorCode: Int? = 404 // nil
//var errorMessage: String? = "Not Found"
ifleterrorCode =errorCode{
ifleterrorMessage =errorMessage{
print("error code is\(errorCode) and error message is\(errorMessage)")
}
}
//简单方式
ifleterrorCode =errorCode, errorMessage =errorMessage{
print("error code is\(errorCode) and error message is\(errorMessage)")
}
//使用三目运算符实现方式二
letmessage =errorMessage==nil?"No Error":errorMessage
//方式四(推荐Swifty风格):nil-coalescing:空聚合解包;语法:??
letmessageTwo =errorMessage??"No Error"
05-function
//: Playground - noun: a place where people can play
importUIKit
varstr ="Hello, playground"
/*1.函数声明
* 2.和可选型结合
* 3.函数返回类型元组
* 4.特殊:内部参数名和外部参数名
*/
//传参是String,没有返回值的函数
funcsayHelloTo(name:String) {
//函数体
print("Hello to\(name)")
}
//调用
sayHelloTo("Maggie")
//没有返回值的函数声明的三种方式
//func sayHelloTo(name: String) {}
//func sayHelloTo(name: String) -> () {}
//func sayHelloTo(name: String) -> Void {}
//给定字符串,返回字符串
funcsayHelloToWithOneParam(name:String) ->String{
letreturnString ="Hello to "+ name
returnreturnString
}
varmessage =sayHelloToWithOneParam("Bob")
//传参是字符串可选型,返回字符串
funcsayHelloToWithOptional(name:String?) ->String{
return"Hello to "+ (name ??"Guest")
}
//调用
varname:String? ="Jonny"
letnewMsg =sayHelloToWithOptional(name)
//需求:给定一个整型类型的数组,返回该数组中的最小值和最大值(元组)
funcfindMaxAndMin(numbers: [Int]) -> (min:Int, max:Int)? {
//处理数组为空
ifnumbers.isEmpty{
returnnil
}
varminValue = numbers[0]
varmaxValue = numbers[0]
fornumberinnumbers {
minValue =min(minValue, number)
maxValue =max(maxValue, number)
}
return(minValue, maxValue)
}
//调用
varscoresOne = [130,105,122,108]
ifletresultOne =findMaxAndMin(scoresOne) {
print("max is\(resultOne.max) and min is\(resultOne.min)")
}
//调用
varscores: [Int]? =nil//[130, 105, 122, 108]
//保证scores不会nil, scores!强制解包没有风险
scores=scores?? []
ifletresult =findMaxAndMin(scores!) {
print("max is\(result.max) and min is\(result.min)")
}
//给定两个字符串类型的参数,返回String类型
funcsayHelloTo(name:String, greeting:String) ->String{
return"\(greeting) to\(name)"
}
//调用
sayHelloTo("Maggie", greeting:"Hello")
//给定两个整型数值,返回乘积
//可以使用下划线来忽略某个/某些个参数的名字(没有歧义的情况)
funcmutipleOf(numberOne:Int,_numberTwo:Int) ->Int{
returnnumberOne * numberTwo
}
//调用
mutipleOf(10,20)
/**func insert(newElement: Element, atIndex i: Int) {
// atIndex:外部参数名;i:内部参数名
array[i]
}
*/
vararray = [1,2,3,50,21]
array.insert(20, atIndex:3)
//内部参数名和外部参数名
//参照物:函数内部还是函数调用外部
//目的:即可以保证函数外部调用的语义明确,又可以保证函数内部的语义明确
funcsayHelloToWithExternal(name:String,withGreetings greeting:String) ->String{
// withGreetings:外部参数名;greeting:内部参数名
return"\(greeting) to\(name)"
}
sayHelloToWithExternal("Bob", withGreetings:"Best wishes to ")
// Impeletion Proposal
06-other-function
//: Playground - noun: a place where people can play
importUIKit
varstr ="Hello, playground"
print(1,2,3,4,5,6)
print(1,2,3, separator:"...", terminator:"!!")
//声明可变函数
funcsayHello(greeting:String, names:String...) {
fornameinnames {
print("\(greeting) to\(name)")
}
}
sayHello("Hello", names:"Bob","Maggie","Jonny")
funcsayHelloTo(names:String...,greeting:String) {
fornameinnames {
print("\(greeting) to\(name)")
}
}
sayHelloTo("Bob","Maggie","Jonny", greeting:"hello")
//只支持一个可变参数的声明
funcsayHelloToTo(name:String, greeting:String) {
varnameValue = name
nameValue ="haldhlajsld"
print("\(greeting) to\(nameValue)")
}
//所有的函数的形参都是常量(let修饰);原因:形参都是值拷贝(data copy)
varone =200
vartwo =100
//声明函数:值进行交换(inout关键词)
funcreverse(inoutfirst:Int,inout_second:Int) {
(first, second) = (second, first)
}
//希望:one=100;two=200
//调用函数(&关键符号)
reverse(&one, &two)
one
two
day02总结
2.switch语句
-> C/OC:只能判断整型类型数据
-> Swift: 只能判断基本数据类型(区间运算符/data binding:值绑定/元组)
3.样例:如何使用switch?
[ 02-switch ]
4.样例:Collection类(容器类): 数组/字典/集合
[ 03-collection ]
可选型Optional (类型):
1.目的:用来控制值的存在性; 要么存在(有值),要么不存在(nil)
2.例子(语法):String? -> 字符串可选型
var newStr: String?= “hello”
newStr = nil
3.为什么新添加可选型?
3.1 例如:将字符串类型转成整型;有可能可以转,有可能无法转;此时需要一种类型(可选型)可以描述这两种情况:
—》字符串String -》 整型Int
var newString = “123”
var intValue =convertToInt(newString)
4. 可选型类型和其它类型结合使用
Int? String? Float? Double?
5.样例:如何声明/初始化可选型?
[ 04-optional ]
—>备注:
a.理解:如何声明可选型;如何进行解包
b. 等讲完枚举类型,再重新讲可选型;当前只需要理解基本语法即可
/1603/08_Swift/Day02/Day02-PM2.zip
6. 函数: 函数名字+参数列表+返回类型+函数体
-> 声明语法:
func函数名字(参数列表) -> 返回类型 {函数体}
-> 函数调用:
var returnValue = 函数名字(参数列表)
7.样例:如何声明/调用函数?
[ 05-function ]
8.样例:函数: 可变个参数; 形参都是不可变的;引用传值(值传值)
[ 06-other-function ]
Day02涉及知识点:
—> switch语句相关:
1. switch对原有C/OC语言进行的扩展,扩展内容如下:
a. 可以对基本的数据类型(Int/Float/Double/Tuple...)进行判定
b. 结合区间运算符将条件限定到某个区间内
c. 使用data binding(数据绑定)机制,可以获取对应的值
d. 结合元组,使用下划线可以忽略某个分量的值
—> 容器类相关:
1. 数组Array:一个/多个类型相同的数据组成的数据结构; 有序且可以重复
1.1 使用var修饰表明该数组为可变数组;使用let修饰表明该数组只能初始化一次,为不可变数组
2. 字典Dictionary:包含一个/多个key和value键值对的数据结构; 无序且不可以重复(key)
3. 集合Set: 包含一个/多个不重复数据的数据结构;无序且不重复
—> 可选型Optional相关:
1.可选型的目的:控制值的存在性;如果存在,表明有值;如果不存在为nil
2. nil不能对任何类型进行赋值,除了可选型
3. 可选型需要和其它类型结合使用;例如:Int? Float? Double? String? Range? 枚举可选型;结构体可选型等等。。。
—> 函数相关:
1. 掌握声明有参数/没有参数/多个参数的函数声明
2. 了解函数和可选型结合的声明方式
3. 了解可变参数的函数声明和调用
4. 理解函数的值传递(value)和引用传递(inference)的概念和使用
—> 语法风格相关:
1. switch语句不需要写break语句
2.switch语句中,对多个条件的判定,使用逗号分隔即可