一.字符串的使用
let wiseWords = "\"I am a handsome\"-boy"
var emptyString = ""
if emptyString.isEmpty{
println("這是一個空值")
}
簡單說明:isEmpty方法是用來判斷字符串是否為空值的,之后會執行if語句中的println方法,因為emptyString是一個空的字符串。
注意:創建一個空的字符串有兩種方法,一是如emptyString = "" ;另一種是通過字符串類實例化一個空的字符串 var emptyAnotherString = String().
假如我們想要遍歷字符串中的每個字符,可以采用 for in,如:
for cha in "dog!"
{println(cha)
}
通過playground可以看出有四個字符輸出:分別是d、o、g、!.
如果想要獲取一個字符串的字符數,可以利用countElements方法:
let unusualMenagerie = "Koala , Snail , Penguin , Dromedary "
println("unusualMenagerie has \(countElements(unusualMenagerie)) characters")
可以看到在playground中輸出這么一段話:"unusualMenagerie has?36 characters".
字符串的大小寫:
大寫:uppercaseString
小寫:lowercaseString
let normal = "Could u help m,please?"
let shouty = normal.uppercaseString
let small = normal.lowercaseString
此時shouty =?"COULD U HELP M,PLEASE?"而small =?"could u help m,please?"
二:數組
首先定義一個可變數組:
//數組
var arr = ["dog","cat","cow"]
可以知道arr數組中包含三個元素,分別是dog、cat、cow
這個時候如果想在原有的數組中再插入一條數據,可以采用如下的方法實現:
//插入
arr.insert("dog", atIndex: 0)
這條語句是在arr索引為0的位置插入dog值,此時的arr數組就有四個有效值,分別是dog、dog、cat、cow
移除數組中指定位置的值(假如移除索引為1處的值):
//移除
let sub = arr.removeAtIndex(1)
如果想要移除數組中最后一個元素的值:
//移除最后一個元素
let sub2 = arr.removeLast()
取出數組中的索引和對應的值:
//取索引和值
for (index,value) in enumerate(arr){
println("Item \(index + 1): \(value)")
}
可以在playground中清楚的看到打印結果如圖示:
三:字典
字典類型寫為字典<KeyType, valueType>,KeyType 可以用作字典鍵的數值類型,valueType 是 字典為那些鍵儲存的數值類型。唯一的局限是 KeyType 必須是 hashable,基本類型(比如 String、Int、Double 和 Bool)都默認為是 hashable
初始化一個字典:
var animals : Dictionary<String,String> = ["dog":"狗", "cat":"貓" ,"cow":"牛"]
修改字典中某一個key對應的value有兩種方式可以選擇:
animals["dog"] = "這是一條狗"
animals.updateValue("小明", forKey: "perple")
其中updateValue(forKey:)的返回值是舊值
想要在原字典中添加一個鍵值對,可以直接以下面這種方式實現:
animals["perple"] = "人"
?