當前位置:成語大全網 - 新華字典 - 蘋果的編程語言 Swift 是用什麽開發的

蘋果的編程語言 Swift 是用什麽開發的

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." }