var name = "Jack"
print("My name is \(name)") // 输出:My name is Jack
print("My name is " + name) // 同样也可以使用 +
// 甚至还能在字符串中进行计算
var age = 23
"You are \(age) years old. In another \(age) years you will be \(age * 2)." //输出:You are 23 years old. In another 23 years you will be 46.
数组
var songs1 = ["Shake it Off", "You Belong with Me", "Back to December"]
// 约定数组内元素类型 String
var songs2: [String] = ["Shake it Off", "You Belong with Me", "Back to December"]
// 数组可包含任意元素
var songs3: [Any] = ["Shake it Off", "You Belong with Me", "Back to December", 3]
创建空数组
var songs1 = [String]()// 常用
var songs2: [String] = []//与基本类型相似的声明赋值方式
拼接数组
var songs = ["Shake it Off", "You Belong with Me", "Love Story"]
var songs2 = ["Today was a Fairytale", "Welcome to New York", "Fifteen"]
var both = songs + songs2
both += ["Everything has Changed"]
var action: String
var stayOutTooLate = true
var nothingInBrain = true
if stayOutTooLate && nothingInBrain {
action = "cruise"
} else if !stayOutTooLate && nothingInBrain {
// do someting
} else {
// do other
}
for 循环
for i in 1 ... 10 {
print(i) // 从1到10
}
for i in 1 ..< 10 {
print(i) // 从1到9
}
// 打印整个数组
var songs = ["Shake it Off", "You Belong with Me", "Love Story"]
for i in 0 ..< songs.count {
print(songs[i])
}
// 不需要获取当前索引,只需要执行固定次数时
for _ in 1 ... 10 {
print("人类的本质是复读机")// 人类的本质是复读机X10
}
..<被称为半开区间
while 循环
var counter = 0
while true {
print("Counter is now \(counter)")
counter += 1
if counter == 556 {
break
}
}
switch
let liveAlbums = 2
switch liveAlbums {
case 0:
print("You're just starting out")
case 1:
print("You just released iTunes Live From SoHo")
case 2:
print("You just released Speak Now World Tour")
default:
print("Have you done something new?")
}
// 使用区间
let studioAlbums = 5
switch studioAlbums {
case 0...1:
print("You're just starting out")
case 2...3:
print("You're a rising star")
case 4...5:
print("You're world famous!")
default:
print("Have you done something new?")
}
环境版本:
var & let 变量与常量
var
:变量,可以随时修改变量代表的值。let
:常量,赋值之后不能修改这个常量代表的值。数据类型
Swift
中不需要声明变量类型,但不代表变量就没有类型Swift
会推断我们需要的变量类型也可以显示的给变量定义它的类型,例如:
var test: String = "Hello World"
数值
Double
的精度要高于Float
,但是也只是有限的高布尔
Swift
中的关键字为Bool
运算符
与其他语言类似的运算符
+
添加,-
减法,*
乘法,/
除法,=
赋值等等为什么同是变量
a
+一个整数,a+3
能通过编译,而a+c
(一个整数变量)却不行?推测:由于
Swift
不同类型不能进行运算,a
为Double
,且c
为Int
,因此不能进行运算。而在变量e
计算中,Swift
推断此处的1
为Double
类型,因此才能通过编译。比较运算符:大于(
>
),大于或等于(>=
),小于(<
),等于(==
),否(!
),不等(!=
)字符串
字符串插值:在字符串中组合变量和常量
数组
创建空数组
拼接数组
字典
键值对形式,类似
Java
中的Map
数据类型if & else
for 循环
..<
被称为半开区间while 循环
switch