1. 程式人生 > >Swift簡單介紹 教程

Swift簡單介紹 教程

div cap ack 語句 apt 聲明數組 [1] unit ++i

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程序。

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?

= "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除了..還有...:..生成前閉後開的區間,而...生成前閉後閉的區間。

Swift簡單介紹 教程