var str : String = "nihao"
var numStr = "4"
var realNumber =5
var sum = numStr + realNumber//这么写编译器会提示error 因为不支持隐式的类型转换var nilStr : String? ="nilOrNotNil"
nilStr = nil
var numStr = "4"
var realNumber =5
var sum =numStr.toInt()! +realNumber
var numbers = [1,5,2,1,6]
var dict = ["isNew" :"yes",
"name" : "Swift"]
numbers[3] =4
numbers = [4,5,6,7,8,9]
var largeThanThree = 0
for n innumbers {
if n > 3 {
largeThanThree++
} else {
largeThanThree--
}
}
largeThanThree //6
遍历字典时可以获取key value
for (question , answer) indict {
if question == "isNew" {
answer //yes
} else {
answer //swift
}
}
对于optional在if语句中的使用需要注意一下
var optionalStr : String? ="swift"
var greeting : String? ="nihao"
optionalStr = nil
if let name = optionalStr {
greeting = "nihao , \(name)" //不会执行
}
但是如果optionalStr 没有被赋值为nil,也就是仍然为"swift"则会给greeting变量赋值为"nihao, swift"
switch语句
Swift的switch支持对String的case比较
let object = "water"
var statement = "the object is "
switch object {
case "ice" :
statement += "冰"
case "water" ,"other":
statement += "水"
default :
statement += "未知"
}
statement //"the object is水"
while语句
var big = Int8.max//127 八位integer最大值
while big > 0 {
big--
}
控制范围的for
把通常的for循环用swift写会是
var loop = 0
for var i = 0; i < 3; i++ {
loop++
}
loop //3
现在swift支持了一种新的语法来完成这种操作
loop = 0
for i in 0..3 {
loop++
}
loop //3
那如果想让i取边界值,可以用0...3来代替0..3
函数
函数在Swift中变得十分灵活起来,它可以支持单一返回值,返回多个值,甚至嵌套函数,返回函数或者用函数作为参数等等。
func sayHello(person name : String, weekday day : String) -> String {
return"hello \(name), today is \(day)"
}
var res = sayHello(person:"mattt", weekday : "monday")
->作为返回值符号, name前的person 属于参数表述,也可以不加直接将值传递进去,这里为了函数方便使用才加上。
可变参数的多返回值
多个不同类型或相同类型的值组成的数据结构Swift里称为元组(tuple)
下面一个函数传入可变参数,使用元组返回多个值
func caculate(numbers: Int...) -> (Int,Int) {
var nSum = 0
var nAvg = 0
for number in numbers {
nSum += number
}
nSum
nAvg = nSum / numbers.count
return (nSum, nAvg)
}
var (s: Int, a: Int) = caculate(1,2,3)
s //6
a //2
嵌套函数
func funs(number : Int) ->Int {
var y = 10 + number
func add() {
y++
}
add()
return y
}
函数也可以作为返回值进行传递
func makeIncrementer() -> (Int ->Int) {
func addOne(number: Int) ->Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
闭包函数
var numbers: Int[] = [4,3,1,2,5]
numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
})
这篇博客简单介绍了Swift初步的使用,如果有不当的地方希望指出。