Swift学习笔记(Page.1)
Hello, Swift!
print("Hello, Swift!")
VarsAndConstants
变量(Vars):
//变量
var a = 1
a = 10
var b = 2
常量(Constants):
//常量
let c = a+b
//error:
//c = 10
Use let to make a constant and var to make a variable. The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once. This means you can use constants to name a value that you determine once but use in many places.
使用 let
来声明常量,使用 var
来声明变量。一个常量的值在编译时并不需要获取,但是你只能为它赋值一次。也就是说你可以用常量来表示这样一个值:你只需要决定一次,但是该值需要使用很多次。
Types
变量在赋值后会自动转化类型,
var str = "Hello"
可以用如下的方法为变量指定类型
var s:String = "World"
var i:Int = 100
var word:String = "Swift"
一般情况下,我们不会指定变量类型,由系统自动指定。
Strings
字符串的拼接
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
//"The width is 94"
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
//"I have 3 apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
//"I have 8 pieces of fruit."
ArrayAndDictionary
数组:
初始化一个数组
var array = []
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
print(shoppingList)
//"["catfish", "bottle of water", "tulips", "blue paint"]\n"
指定数组中元素的类型为String
let emptyArray = [String]()
var stringArray:[String] = ["A", "B", "C"]
字典:
初始化一个字典
var dict = [:]
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
print(occupations)
//"["Kaylee": "Mechanic", "Jayne": "Public Relations", "Malcolm": "Captain"]\n"
指定字典中键(Key)的类型为String
,值(Value)的类型为Float
let emptyDictionary = [String: Float]()
var stringDictionary[String:Float] = ["age":18]
Control Flow
For
var arr:[String] = []
for index in 0...9 {
arr.append("Item \(index)")
}
//for index in 0..<9 {
// arr.append("Item \(index)")
//}
print(arr)
//["Item 0", "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7", "Item 8", "Item 9"]
for value in arr {
print(value)
}
var dict = ["name":"Swift", "age":18]
for (key, value) in dict {
print("\(key), \(value)")
}
//age, 18
//name, Swift
While
var n = 2
while n < 100 {
n = n * 2
}
print(n)
//128
var m = 2
repeat {
m = m * 2
} while m < 100
print(m)
//128
Switch
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.")
}
//"Is it a spicy red pepper?\n"
Flow(控制流)
let individualScores = [75, 43, 103, 87, 12]
var teamScore = 0
for score in individualScores {
if score > 50 {
teamScore += 3
} else {
teamScore += 1
}
}
print(teamScore)
//"11\n"