swift是什麼?
swift是蘋果於wwdc 2014發布的編程語言,這裡引用the swift programming language的原話:
swift is a new programming language for ios and os x apps that builds on the best of c and objective-c without the constraints of c compatibility.
swift adopts safe programming patterns and adds modern features to make programming easier more flexible and more fun.
swift’s clean slate backed by the mature and much-loved cocoa and cocoa touch frameworks is an opportunity to imagine how software development works.
swift is the first industrial-quality systems programming language that is as expressive and enjoyable as a scripting language.
簡單的說:
swift用來寫ios和os x程序。(估計也不會支持其它屌絲系統)
swift吸取了c和objective-c的優點,且更加強大易用。
swift可以使用現有的cocoa和cocoa touch框架。
swift兼具編譯語言的高性能(performance)和腳本語言的交互性(interactive)。
swift語言概覽
基本概念
注:這一節的代碼源自the swift programming language中的a swift tour。
hello world
類似於腳本語言,下面的代碼即是一個完整的swift程序。
1
println(" hello world" )
變量與常量
swift使用var聲明變量,let聲明常量。
1
2
3
var myvariable = 42
myvariable = 50
let myconstant = 42
類型推導
swift支持類型推導(type inference),所以上面的代碼不需指定類型,如果需要指定類型:
1
let explicitdouble : double = 70
swift不支持隱式類型轉換(implicitly casting),所以下面的代碼需要顯式類型轉換(explicitly casting):
1
2
3
let label = " the width is "
let width = 94
let width = label + string(width)
字符串格式化
swift使用(item)的形式進行字符串格式化:
1
2
3
4
let apples = 3
let oranges = 5
let applesummary = " i have (apples) apples."
let applesummary = " i have (apples + oranges) pieces of fruit."
數組和字典
swift使用[]操作符聲明數組(array)和字典(dictionary):
1
2
3
4
5
6
7
8
var shoppinglist = [" catfish" " water" " tulips" " blue paint" ]
shoppinglist[1] = " bottle of water"
var occupations = [
" malcolm" : " captain"
" kaylee" : " mechanic"
]
occupations[" jayne" ] = " public relations"
一般使用初始化器(initializer)語法創建空數組和空字典:
1
2
let emptyarray = string[]()
let emptydictionary = dictionary< string float> ()
如果類型信息已知,則可以使用[]聲明空數組,使用[:]聲明空字典。
控制流
概覽
swift的條件語句包含if和switch,循環語句包含for-in、for、while和do-while,循環/判斷條件不需要括號,但循環/判斷體(body)必需括號:
1
2
3
4
5
6
7
8
9
let individualscores = [75 43 103 87 12]
var teamscore = 0
for score in individualscores {
if score > 50 {
teamscore += 3
} else {
teamscore += 1
}
}
可空類型
結合if和let,可以方便的處理可空變量(nullable variable)。對於空值,需要在類型聲明後添加?顯式標明該類型可空。
1
2
3
4
5
6
7
8
var optionalstring: string? = " hello"
optionalstring == nil
var optionalname: string? = " john appleseed"
var gretting = " hello!"
if let name = optionalname {
gretting = " hello (name)"
}
靈活的switch
swift中的switch支持各種各樣的比較操作:
1
2
3
4
5
6
7
8
9
10
11
let vegetable = " red pepper"
switch vegetable {
case " celery" :
let vegetablecomment = " add some raisins and make ants on a log."
case " cucumber" " watercress" :
let vegetablecomment = " that would make a good tea sandwich."
case let x where x.hassuffix(" pepper" ):
let vegetablecomment = " is it a spicy (x)?"
default:
let vegetablecomment = " everything tastes good in soup."
}