字符串和字符
表现形式
var dollarSign: Character = "$"
var myFirstSwiftString: String = "mo' money"
var mySecondSwiftString: String = "mo' problems"
var concatenatedString = myFirstSwiftString + ", " + mySecondSwiftString
//显示其类型
concatenatedString.dynamicType
遍历字符串中的字符数组
var password = "Meet me in St. Louis"
for character in password.characters {
if character == "e" {
print("found an e!")
} else {
}
}
字符串中取值字符
尾字符
var lastLetter = word.removeAtIndex(word.endIndex.predecessor())
首字符
var firstLetter = word.removeAtIndex(word.startIndex)
将字符串转成数组,取出第一个
var word = "tan"
var firstLetter = Array(word.characters)[0]
字符串
表现形式
纯字符串
var s:Character = "美"
var quote1 = "\'"
var quote2 = "\u{22}"
带变量的字符串
print("quote1的值为:\(quote1),quote2的值为:\(quote2)")
带表达式的字符串
var lbsPerDay = 0.75
var daysPerMonth:Double = 30.0
doggyDiet = "\(dogName) eats \(lbsPerDay * daysPerMonth)lbs of dog food per month"
Swift中的字符串是结构体,而NSString中的字符串是Class.Swift中的字符串也可以使用NSString方法
let newPassword = password.stringByReplacingOccurrencesOfString("e", withString: "3")
- 单个字符来指定字符常量,如“A”,“9”
- 转义字符表示特殊字符常量,如”\n”,”\t”
- 使用\u{n}的Unicode形式,n代表一个1~8位的十六进制
- 必须用双引号包起来
- Swift中的每一个字符代表了一个可扩展字母集
字符串创建
方法1:直接赋值
var str1 = "Jike"
方法2:构造函数
var str2 = String()
//创建多个重复字符的字符串
var str3 = String(count:4,repeatedValue:Character("a"))
var strRep = String(count:4,repeatedValue:UnicodeScalar("xxxxx")) //使用unicode
print(strRep)
初始化空字符串
// Here's one way to initialize an empty Swift string
var characterPoorString = ""
// And here's another
let potentialRichString = String()
characterPoorString.characters
字符串是否为空
print(str3.isEmpty)
字符串拼接
方式1.用 “+”
var str4 = str1 + "College"
str1 += "Hello"
print(str4)
方式2.用append
let char:Character = "!"
str1.append(char)
print(str1)
字符数量
Swift1.x
print("str3 has \(countElements(str3)) characters")
Swift2.x
print("str3 has \(str4.characters.count) characters")
这两种的输出结果不一样
var nWithTilde = "\u{006E}\u{0303}"
nWithTilde.unicodeScalars.count
nWithTilde.characters.count //通常用这个
- Swift中的Unicode16Count函数所获得的值,才是和NSString中的length一样。因为SWIFT的count是基于Unicode,而OC的length是基于UTF-16
- Swift中的字符串是否可以修改仅通过定义的是变量还是常量来决定,也就是var or let
字符串比较
let quotation = "We are the same"
let sameQuotation = "We are the same"
if quotation == sameQuotation {
print("These are the same")
}
字符串是否有特定的前缀后缀
var food = ["Fruits:apple",
"Fruits : orange",
"Fruits : banana",
"Vegetables: tomato",
"Vegetables: potato"]
for fry in food{
if fry.hasPrefix("Fruits"){
print(fry)
}
if fry.hasSuffix("o"){
print(fry)
}
}
字符串是否包含某子字符串
let word = "fortunate"
if word.rangeOfString("tuna") != nil {
print("yes")
}
替换子字符串
let lottaLikes = "If like, you wanna learn Swift, like, you should build lots of small apps, cuz it's like, a good way to practice."
let noLikes = lottaLikes.stringByReplacingOccurrencesOfString("like, ", withString: "")
字符串转为整形
Swift 1.x
let myString: String = "256"
let myInt: Int? = myString.toInt()
Swift 2.x
let myString: String = "256"
let myInt: Int? = Int(myString)
字符串大小写转换
let didYouKnowString = "Did you know that the Swift String class comes with lots of useful methods?"
let whisperString = "psst" + ", " + didYouKnowString.lowercaseString
集合
数组
数组的创建
方式1
var numbers = Array<Double>() //Array<Double>.init 后面省略了init方法
方式2
var moreNumbers = [Double]()
moreNumbers = [85.0, 90.0, 95.0]
方式3
let differentNumbers = [97.5, 98.5, 99.0]
数组合并
moreNumbers = moreNumbers + differentNumbers
数组可持有任何类型对象
var circuit = [livingRoomSwitch, kitchenSwitch, bathroomSwitch]
数组尾部添加
var roadTripMusic = ["Neil Young","Kendrick Lamar","Flo Rida", "Nirvana"]
roadTripMusic.append("Rae Sremmurd")
数组插入
roadTripMusic.insert("Dej Loaf", atIndex: 2)
数组删除
roadTripMusic.removeAtIndex(3)
数组计数
roadTripMusic.count
数组取值
let musician = roadTripMusic[2]
数组替换
food[0...2] = ["a","b"]
//从第一个到第三个元素进行替换,但只有两个元素,第三个将被删除,被“没有”所替换
数组删除最后一项
food.removeLast()
数组删除所有
food.removeAll(keepCapacity:false)
字典
字典创建
方式1
var groupsDict = [String:String]()
方式2
var animalGroupsDict = ["whales":"pod", "geese":"flock", "lions": "pride"]
var averageLifeSpanDict = [String:Range<Int>]()
var lifeSpanDict = ["African Grey Parrot": 50...70, "Tiger Salamander": 12...15, "Bottlenose Dolphin": 20...30]
空字典
var emptyDic:[String:Double] = [:]
print(emptyDic.isEmpty)
字典添加
animalGroupsDict["crows"] = "murder"
animalGroupsDict["monkeys"] = "troop"
字典计数
animalGroupsDict.count
字典删除
animalGroupsDict["crows"] = nil
移除单个值
person.removeValueForKey("name")
移除所有值
person.removeAll(keepCapacity:false)
字典更新
方式1
animalGroupsDict["monkeys"] = "barrel"
方式2:返回值为optional类型,如果该key存在,则赋新值,返回old value,如果key不存在,则赋值,同时返回nil
var group = animalGroupsDict.updateValue("gaggle", forKey: "geese")
字典取值
字典取值所返回的是optional,因为很可能没有该key,所以使用前需要用if let unwrap
let groupOfWhales = animalGroupsDict["whales"]
if let groupOfWhales = animalGroupsDict["whales"] {
print("We saw a \(groupOfWhales) of whales from the boat.")
} else {
print("No value found for that key.")
}
字典键和值的取出
let keysArr = [String](person.keys)
let valueArr = [String](person.values)
print(valuesArr)
字典的遍历
字典的遍历后,返回时元组类型
for (key,value) in person{
print("\(key):\(value)")
}
字典的使用
这种的声明是不严谨的,因为值的类型都不是一样的,系统会推断它是NSObject类型
字典的key or value 通常最好是同一类型,否则强制解析时会出错
var person = ["age":18,"name":"Tom","身高":178]
这样会报错,因为是将NSObject转为int
var height:Int? = person["身高"]
if height != nil {
print(height!)
}
以下才正确
var person = ["age":"18","name":"Tom","身高":"178"]
var height:String? = person["身高"]
if height != nil {
print(height!)
}
print(person["age"])
Set - 无序且不能有相同的元素
集合创建
方式1
var utensils = Set<String>()
var trees = Set<Character>()
var flowers:Set<Character> = ["🌷","🌹","🌸"]
方式2
var cutlery: Set = ["fork", "knife", "spoon"]
集合的操作
trees.insert("🌲")
trees.insert("🌳")
trees.insert("🌵")
trees.remove("🌵")
trees.count
AnyObject and Any
Swift中有两种特殊的object:
- Any:表示任何数据类型
- AnyObject:表示任何对象
1 | //因为数组里的数据不一样,这里的数组默认是AnyObject类型,因为他们都不一样 |
for fruit in food{
fruit = "good" //error, fruit默认是let类型
}