坚持 成长 每日一篇
let 和var
以下是let和var使用过程中注意的事项
- 使用let定义的数组不能通过append来添加新的元素
字符串
- 可以使用加号拼接两个字符串
- String()可以把基本数据类型转化为字符串
- ()组合替换了原来的占位符模式
字符串可以通过在()之前加\来转意变量或者表达式
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit.”
摘录来自: Apple Inc. “The Swift Programming Language (Swift 2.1)”。 iBooks.
数组和字典
- 数组支持范型(貌似OC时候也支持)
- 数组,字典里面的value可以是基本数字类型
- []方式创建的数组变量是可变数组,常量是不可变数组
- 4.
可以使用[]创建一个数组(此数组为可变数组)或者字典(可变字典),使用索引下标引用
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations”
摘录来自: Apple Inc. “The Swift Programming Language (Swift 2.1)”。 iBooks. https://itun.es/cn/jEUH0.l
可以使用[]或者[:]来创建一个空的数组货字典!如果数组或字典的类型确定可以String或者String:float来创建预定类型的空数组货字典(注意:这里的数组似乎只接受String类型)
let emptyArray = [String]()
let emptyDictionary = [String:Float]()
//类型不确定时
let emptyArray = []
let emptyDictionary = [:]
swift的数组里面还能定义存放数字的数组,通过for .. in ..{}遍历数组中元素
let individualScores = [75,43,103,87,12]
var teamScore = 0
for score in individualScores{
if score > 50{
teamScore += 3
}else{
teamScore += 1
}
}
if语句的使用
使用if … {}语句,对于if后面必须跟的是表达式语句,你可以结合let使用让变量在{}使用另外一个变量名,但是如果变量为空,{}是不会被执行的
var optionName:String? = "John Appleseed"
//if optionalName is nil,the code in {} would not be run
if let name = optionalName {
}
for (key,value) in ..{}来便利字典
let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]
var largest = 0
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
}
}
}
摘录来自: Apple Inc. “The Swift Programming Language (Swift 2.1)”。 iBooks. https://itun.es/cn/jEUH0.l
..??..表示如果前面的值为nil则使用后面的值
let nickName: String? = nil
let fullName: String = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"
//informalGreeting = "Hi John Appleseed"
switch语句的使用
1.switch可以比较字符串,switch后跟的不仅仅是数字了,还有可以是对象
2.case不需要使用break
3.default是不可少的否则会出错
4.可以结合let .. where ..来判断是否部分符合条件
let vegetable = "red pepper"
switch vegetable {
case "celery":
print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
print("Is it a spicy \(x)?")
default:
print("Everything tastes good in soup.")
}
摘录来自: Apple Inc. “The Swift Programming Language (Swift 2.1)”。 iBooks. https://itun.es/cn/jEUH0.l
方法和闭包
- ->来分开返回值与函数名(包括参数)
- 使用方法时候,第一个参数的别名可省略
- 方法的返回值可以是一个另一个方法
- 方法可以内嵌方法
- 方法参数个数可以像C那样可变,可变个数的参数会被保存在一个数组里面