常量和變量
常量和變量把一個名字(比如maximumNumberOfLoginAttempts或者welcomeMessage)和一個指定類型的
值(比如數(shù)字10或者字符串"Hello")關(guān)聯(lián)起來蛛枚。常量的值一旦設(shè)定就不能改變,而變量的值可以隨意更
1.聲明一個 常量?
let a = "Hello World"
如果想明確這個常量的類型
( 在swift 里每句結(jié)束后不是必須使用“;” 分號 ,? 有一種情況下必須要用分號,即你打算在同一行內(nèi)寫多條獨立的語句 )?
let? a : string =? "Hello World"? ? ? ? ;? ? let myVariable ?:float_t ?= ?42
1.聲明一個 變量
var a = "Hello World"
a = "Haha"
打印信息
print( a ) ? ?// ?print( \( a ) )
//? ? ? ? 初始化空字符串
let stringA = ""
let stringB = String()
if stringA.isEmpty && stringB.isEmpty{
print("他倆是空的,Nothing to see here")
}
//字符串的拼接 ? ?直接用" + "
let a = "The width is "
let b = 94
let widthLabel = a + String(b) // 轉(zhuǎn)換成string 類型
print(widthLabel)
創(chuàng)建一個空數(shù)組
var emptyArray = [String]()
向數(shù)組中插入一個數(shù)據(jù) ? append
emptyArray.append(a)
print(emptyArray)
//遍歷數(shù)組 ? 和判斷 ?
遍歷一般用 ?for in ? ? ?判斷則不用if(){} ? 直接 用if ?{} ?
let value = [22,11,77,33,44,55]
for scoree in value{
if scoree > 30{
print("aaaaaaa")
}else{
print("bbbbbbb")
}
if scoree > 20 {
let name = "Hello World"
print(name)
}
}
//兩個數(shù)組相加
let oneArray = ["1","2","3"]
let? twoArray? = ["4","5","6"]
var threeArray = oneArray + twoArray
//? 遍歷數(shù)組? 然后根據(jù)下表刪除
for (index,value) in threeArray.enumerated() {
if value == "3" {
threeArray.remove(at: index)
}
}
print(threeArray)
Tuples 元組
元組(tuples)把多個值組合成一個復(fù)合值。元組內(nèi)的值可以是任意類型,并不要求是相同類型。
let http404Error = (404, "Not Found")
// http404Error 的類型是 (Int, String),值是 (404, "Not Found")
你可以把任意順序的類型組合成一個元組,這個元組可以包含所有類型腹纳。只要你想,你可以創(chuàng)建一個類型為( Int , Int ,Int)或者 (string, Bool) 或者其他任何你想要的組合的元組九杂。
你可以將一個元組的內(nèi)容分解(decompose)成單獨的常量和變量,然后你就可以正常使用它們了:
let (statusCode, statusMessage) = http404Errorprint("The status code is \(statusCode)")
// 輸出 "The status code is 404"
print("The status message is \(statusMessage)")// 輸出 "The status message is Not Found"
如果你只需要一部分元組值,分解的時候可以把要忽略的部分用下劃線(_)標(biāo)記:
let (justTheStatusCode, _) = http404Error
print("The status code is \(justTheStatusCode)")
// 輸出 "The status code is 404"
此外,你還可以通過下標(biāo)來訪問元組中的單個元素,下標(biāo)從零開始:
print("The status code is \(http404Error.0)")
// 輸出 "The status code is 404"
print("The status message is \(http404Error.1)")// 輸出 "The status message is Not Found"
你可以在定義元組的時候給單個元素命名:
let http200Status = (statusCode: 200, description: "OK")
給元組中的元素命名后,你可以通過名字來獲取這些元素的值:
print("The status code is \(http200Status.statusCode)")
// 輸出 "The status code is 200"
print("The status message is \(http200Status.description)")// 輸出 "The status message is OK"
作為函數(shù)返回值時,元組非常有用。一個用來獲取網(wǎng)頁的函數(shù)可能會返回一個(Int, String)元組來描述是否獲取成功宣蠕。和只能返回一個類型的值比較起來,一個包含兩個不同類型值的元組可以讓函數(shù)的返回信息更有用
可選類型
基本就是 返回值的時候如果不確定 是 不是空 或者返回來的是不是 一個確定的類型 就用一個例隆??
var surveyAnswer: String? ? ? ? // surveyAnswer 被自動設(shè)置為 nil
if? 判斷語句 基本語法跟Objective-C ?一樣 ? 在|| 的語句中 ?如果想強調(diào)某個條件是首先判斷的話 ? ?
let a = true
let b = true
let c = true
if a || b || (c){
print("I don't want? say something。抢蚀。镀层。")
}