02-switch
//: Playground - noun: a place where people can play
importUIKit
varstr ="Hello, playground"
/* 1.不需要加break
* 2.必須窮舉所有的可能性
*/
//判定字符串所在分支
letrating ="A"http:// 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語句和區(qū)間運算符結合
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"]
//創(chuàng)建空的可變數組(元素的個數為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: 只能判斷基本數據類型(區(qū)間運算符/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. 結合區(qū)間運算符將條件限定到某個區(qū)間內
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語句中脊僚,對多個條件的判定相叁,使用逗號分隔即可