苹果开发者用计算机语言,苹果的编程语言 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 = 70Swift不支持隱式類型轉換(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()如果類型信息已知,則可以使用[]聲明空數組,使用[:]聲明空字典。控制流概覽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)" }靈活的switchSwift中的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." }
總結
以上是生活随笔為你收集整理的苹果开发者用计算机语言,苹果的编程语言 Swift 是用什么开发的?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 递归的理解
- 下一篇: HTML5新特征、窍门和技术(16~20