Swift可以使用現有的Cocoa和Cocoa Touch框架。express
Swift兼具編譯語言的高性能(Performance)和腳本語言的交互性(Interactive)。
Swift語言概覽
基本概念
注:這一節的代碼源自The Swift Programming Language中的A Swift Tour。
Hello, world
相似於腳本語言。如下的代碼便是一個完整的Swift程序。
println("Hello, world") 變量與常量
Swift使用var聲明變量,let聲明常量。
var myVariable = 42
myVariable = 50
let myConstant = 42
類型推導
Swift支持類型推導(Type Inference),因此上面的代碼不需指定類型。假設需要指定類型:
let explicitDouble : Double = 70
Swift不支持隱式類型轉換(Implicitly casting),因此如下的代碼需要顯式類型轉換(Explicitly casting):
let label = "The width is "
let width = 94
let width = label + String(width)
字符串格式化
Swift使用\(item)的形式進行字符串格式化:
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let appleSummary = "I have \(apples + oranges) pieces of fruit."
數組和字典
Swift使用[]操做符聲明數組(array)和字典(dictionary):
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
var occupations = [
"Malcolm": "Captain",
"Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
通常使用初始化器(initializer)語法建立空數組和空字典:
let emptyArray = String[]()
let emptyDictionary = Dictionary<String, Float>()
假設類型信息已知。則可以使用[]聲明空數組。使用[:]聲明空字典。
控制流
概覽
Swift的條件語句包括if和switch,循環語句包括for-in、for、while和do-while,循環/推斷條件不需要括號,但循環/推斷體(body)必需括號:
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)。對於空值,需要在類型聲明後加入?編程
顯式標明該類型可空。數組
var optionalString: String? = "Hello"
optionalString == nil
var optionalName: String?app
= "John Appleseed"
var gretting = "Hello!"
if let name = optionalName {
gretting = "Hello, \(name)"
}
靈活的switch
Swift中的switch支持各類各樣的比較操做:
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."
}
其餘循環
for-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
}
}
}
largest
while循環和do-while循環:
var n = 2
while n < 100 {
n = n * 2
}
n
var m = 2
do {
m = m * 2
} while m < 100
m
Swift支持傳統的for循環。此外也可以經過結合..(生成一個區間)和for-in實現相同的邏輯。
var firstForLoop = 0
for i in 0..3 {
firstForLoop += i
}
firstForLoop
var secondForLoop = 0
for var i = 0; i < 3; ++i {
secondForLoop += 1
}
注意:Swift除了..還有...:..生成前閉後開的區間,而...生成前閉後閉的區間。框架