swift 简明教程
在IOS8的WWDC发布会上,一款叫做Swift的编程语言发布了。Swift对比Oc显得十分的现代化,它被人们看作“快速 现代化 且安全 有趣”的一门编程语言。而且swfit的编程语法 似乎对web开发者更加友好。如果你对javascript有点了解 那么你很快就能用好swift了。Along with the announcement of iOS 8 and Yosemite, Apple surprised all developers in the WWDC by launching a new programming language called Swift. At AppCoda, we’re all excited about the release of Swift. We enjoy programming in Objective-C but the language has showed its age (which is now 30 years old) as compared to some modern programming languages like Ruby. Swift is advertised as a “fast, modern, safe, interactive” programming language. The language is easier to learn and comes with features to make programming more productive. It seems to me Swift is designed to lure web developers to build apps. The syntax of Swift would be more familiar to web developers. If you have some programming experience with Javascript (or other scripting languages), it would be easier for you to pick up Swift rather than Objective-C.
如果你观看了WWDC的视频,那么你一定会被一个叫做“playgrounds”的特性所吸引,这个特性可以在你使用Swift做编程的时候,实时的预览结果。换句话说,你不再需要编译运行后,才能在模拟器中看到程序的运行状况,这省却了一次又一次的编译。If you’ve watched the WWDC keynote, you should be amazed by an innovative feature calledPlaygrounds that allow you to experiment Swift and see the result in real-time. In other words, you no longer need to compile and run your app in the Simulator. As you type the code in Playgrounds, you’ll see the actual result immediately without the overheads of compilation
当然 Swift发布的时间不长,大家都对它一直半解,它究竟是什么语法?怎么样去编写 去执行,我也一样不了解,不过好在有官方的文档,简单看一下。At the time of this writing, Swift has only been announced for a week. Like many of you, I’m new to Swift. I have downloaded Apple’s free Swift book and played around with Swift a bit. Swift is a neat language and will definitely make developing iOS apps more attractive. In this post, I’ll share what I’ve learnt so far and the basics of Swift.
变量 常量 和类型推断(昨天 今天 和明天 xiuliuloulou~ 瓦斯果实的那个sb)Variables, Constants and Type Inference
你可以使用var来定义一个变量 使用let来定义一个常量In Swift, you declare variables with the “var” keyword and constants using the “let” keyword. Here is an example:
1 2 | var numberOfRows = 30 let maxNumberOfRows = 100 |
区别就是let关键字定义的量的值是不可变的,而var定义的是可变的。These are the two keywords you need to know for variable and constant declaration. You simply use the “let” keyword for storing value that is unchanged. Otherwise, use “var” keyword for storing value that can be changed.
有趣的是swift允许你使用 任何类字符的符合作为变量或常量名,下面是有表情符号的变量。What’s interesting is that Swift allows you to use nearly any character for both variable and constant names. You can even use emoji character for the naming:
你也许已经发现了swift和Oc声明使用变量的不同,那就是swift无须声明变量类型。You may notice a huge difference in variable declaration between Objective C and Swift. In Objective-C, developers have to specify explicitly the type information when declaring a variable. Be it an int or double or NSString, etc.
1 2 3 |
由于类型推断这一强大特性的加入,swift的编译器可以动态识别变量类型。It’s your responsibility to specify the type. For Swift, you no longer needs to annotate variables with type information. It provides a huge feature known as Type inference. The feature enables the compiler to deduce the type automatically by examining the values you provide in the variable.
1 2 3 4 5 6 | let count = 10 // count is inferred to be of type Int var price = 23.55 // price is inferred to be of type Double var myMessage = "Swift is the future!" // myMessage is inferred to be of type String |
对比Oc swift这样做 应该是简单了许多,当然swift还是允许声明时指定变量类型,如下:It makes variable and constant declaration much simpler, as compared to Objective C. Swift provides an option for you to explicitly specify the type information if you wish. The below example shows how to specify type information when declaring a variable in Swift:
1 | var myMessage : String = "Swift is the future!" |
不需要分号No Semicolons
也许你早就习惯了分号 但是现在真的不需要了。In Objective C, you need to end each statement in your code with a semicolon. If you forget to do so, you’ll end up with a compilation error.
swift允许你不在行末加分号,当然如果你想加 也是可以的。(这是病,可以不治)As you can see from the above examples, Swift doesn’t require you to write a semicolon (;) after each statement, though you can still do so if you like.
1 | var myMessage = "No semicolon is needed" |
基础的字符串操作(字符串撑起了半边天)Basic String Manipulation
Swift 使用String来作为字符串类型的声明。字符串是现代化的也就是Unicode的。In Swift, strings are represented by the String type, which is fully Unicode-compliant. You can declare strings as variables or constants:
1 2 | let dontModifyMe = "You cannot modify this string" var modifyMe = "You can modify this string" |
在Oc中你不得不在NSString和NSMutableString中做出选择。现在在Swift中你可以不必如此了。In Objective C, you have to choose between NSString and NSMutableString classes to indicate whether the string can be modified. You do not need to make such choice in Swift. Whenever you assign a string as variable (i.e. var), the string can be modified in your code.
你可以直接使用“+”来拼接字符串。Swift simplifies string manipulating and allows you to create a new string from a mix of constants, variables, literals, as well as, expressions. Concatenating strings is super easy. Simply add two strings together using the “+” operator:
1 2 3 4 5 | let firstMessage = "Swift is awesome. " let secondMessage= "What do you think?" var message = firstMessage + secondMessage println(message) |
下面是结果,println 是一个全局方法,对于不怎么操作日志的朋友(比如说我,用途还是极大的,日志好,还是要改掉不好的习惯)Swift automatically combines both messages and you should the following message in console. Note that println is a global function in Swift to print the message in console.
1 | Swift is awesome. What do you think? |
看看Oc要怎么做?可读性是多么的不太好啊。You can do that in Objective C by using stringWithFormat: method. But isn’t the Swift version more readable?
1 2 3 4 5 |
Swift还提供==来直接判断字符串是否一样,在Oc 你也许要用isEqualToString来试试。String comparison is more straightforward. In Objective C, you can’t use the == operator to compare two strings. Instead you use the isEqualToString: method of NSString to check if both strings are equal. Finally, Swift allows you to compare strings directly by using the == operator.
1 2 3 4 5 | var string1 = "Hello" var string2 = "Hello" if string1 == string2 { println("Both are the same") } |
数组(又是一个)Arrays
数组的声明语法 swift和Oc还是有点像的。The syntax of declaring an array in Swift is similar to that in Objective C. Here is an example:
Objective C:
1 | NSArray *recipes = @[@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger", @"Ham and Egg Sandwich"]; |
Swift:
1 | var recipes = ["Egg Benedict", "Mushroom Risotto", "Full Breakfast", "Hamburger", "Ham and Egg Sandwich"] |
当然由于类型推断 你不必再为类型发愁了。While you can put any objects in NSArray or NSMutableArray in Objective C, arrays in Swift can only store items of the same type. Say, you can only store strings in the above string array. With type inference, Swift automatically detects the array type. But if you like, you can also specify the type in the following form:
1 | var recipes : String[] = ["Egg Benedict", "Mushroom Risotto", "Full Breakfast", "Hamburger", "Ham and Egg Sandwich"] |
Like NSArray, the Swift provides various methods for you to query and manipulate an array.
数组中元素个数Simply use the count method to find out the number of items in the array:
1 2 | var numberOfItems = recipes.count // recipes.count will return 5 |
在swift中你可以直接使用+=来为数组添加一个元素。In Objective C you use the addObject: method of NSMutableArray to add a new item to an array. Swift makes the operation even simpler. You can add an item by using the “+=” operator:
1 | recipes += "Thai Shrimp Cake" |
下面就可添加一系列的元素或数组合并。This applies when you need to add multiple items:
1 | recipes += ["Creme Brelee", "White Chocolate Donut", "Ham and Cheese Panini"] |
通过索引序号即可获取和改变元素。To access or change a particular item in an array, pass the index of the item by using subscript syntax just like that in Objective C.
1 2 | var recipeItem = recipes[0] recipe[1] = "Cupcake" |
语法糖 声明范围One interesting feature of Swift is that you can use “…” to change a range of values. Here is an example:
1 | recipes[1...3] = ["Cheese Cake", "Greek Salad", "Braised Beef Cheeks"] |
This changes the item 2 to 4 of the recipes array to “Cheese Cake”, “Greek Salad” and “Braised Beef Cheeks”.
字典Dictionaries
swift提供2中集合类类型,一个是数组另一个也就是字典了。字典可以使用自定义的键。这个和Oc中的NSDictionary相似。Swift only provides two collection types. One is arrays and the other is dictionaries. Each value in a dictionary is associated with a unique key. If you’re familiar with NSDictionary in Objective C, the syntax of initializing a dictionary in Swift is quite similar. Here is an example:
Objective C:
1 | NSDictionary *companies = @{@"AAPL" : @"Apple Inc", @"GOOG" : @"Google Inc", @"AMZN" : @"Amazon.com, Inc", @"FB" : @"Facebook Inc"}; |
Swift:
1 | var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"] |
这样的键值关系可以做下面的类型声明。The key and value in the key-value pairs are separated by a colon. Like array and other variables, Swift automatically detects the type of the key and value. However, if you like, you can specify the type information by using the following syntax:
1 | var companies: Dictionary<String, String> = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"] |
使用for-in循环可以遍历字典中的元素。To iterate through a dictionary, use the for-in loop.
1 2 3 | for (stockCode, name) in companies { println("\(stockCode) = \(name)") } |
也可以是用key和values方法直接获取字典中的的键和值。You can also use the keys and values properties to retrieve the keys and values of the dictionary.
1 2 3 | for stockCode in companies.keys { println("Stock code = \(stockCode)") } |
1 2 3 | for name in companies.values { println("Company name = \(name)") } |
可以同键来直接访问操作键对应的值。To access the value of a particular key, specify the key using the subscript syntax. If you want to add a new key-value pair to the dictionary, simply use the key as the subscript and assign it with a value like below:
1 | companies["TWTR"] = "Twitter Inc" |
Now the companies dictionary contains a total of 5 items. The “TWTR”:”Twitter Inc” pair is automatically added to the companies dictionary.
类Classes
在Oc中你要创建.h和.m来使用类。在swift这些都不需要了。你只需定义一个.swift文件即可。In Objective C, you create separate interface (.h) and implementation (.m) files for classes. Swift no longer requires developers to do that. You can define classes in a single file (.swift) without separating the external interface and implementation.
下面就是一个简单的类。To define a class, you use the class keyword. Here is a sample class in Swift:
1 2 3 4 5 | class Recipe { var name: String = "" var duration: Int = 10 var ingredients: String[] = ["egg"] } |
Similar to Objective C, right? In the above example, we define a Recipe class with three properties including name duration and ingredients. Swift requires you to provide the default values of the properties. You’ll end up with compilation error if the initial values are missing.
如何你不想为变量赋默认值,那么直接在变量声明后面使用?。What if you don’t want to assign a default value? Swift allows you to write a question mark (?) after the type of a value to mark the value as optional.
1 2 3 4 5 | class Recipe { var name: String? var duration: Int = 10 var ingredients: String[]? } |
下面的代码就是声明了一个对象。In the above code, the name and ingredients properties are automatically assigned with a default value of nil. To create an instance of a class, just use the below syntax:
1 | var recipeItem = Recipe() |
也就可以操作对象的属性和方法了。You use the dot notation to access or change the property of an instance.
1 2 3 | recipeItem.name = "Mushroom Risotto" recipeItem.duration = 30 recipeItem.ingredients = ["1 tbsp dried porcini mushrooms", "2 tbsp olive oil", "1 onion, chopped", "2 garlic cloves", "350g/12oz arborio rice", "1.2 litres/2 pints hot vegetable stock", "salt and pepper", "25g/1oz butter"] |
Swift允许你继承 Oc的类和适配协议。例如:Swift allows you to subclass Objective-C classes and adopt Objective-C protocols. For example, you have a SimpleTableViewController class that extends from UIViewController class and adopts both UITableViewDelegate and UITableViewDataSource protocols. You can still use the Objective C classes and protocols but the syntax is a bit different.
Objective C:
1 | @interface SimpleTableViewController : UIViewController <UITableViewDelegate, UITableViewDataSource> |
Swift:
1 | class SimpleTableViewController : UIViewController, UITableViewDelegate, UITableViewDataSource |
方法Methods
Swift允许你在类结构中定义方法。Swift allows you to define methods in class, structure or enumeration. I’ll focus on instance methods of a class here. You can use the func keyword to declare a method. Here is a sample method without return value and parameters:
1 2 3 4 5 | class TodoManager { func printWelcomeMessage() { println("Welcome to My ToDo List") } } |
In Objective C, you call a method like this:
1 | [todoManager printWelcomeMessage]; |
调用方法In Swift, you call a method by using dot syntax:
1 | todoManager.printWelcomeMessage() |
如果你想定义一个接受参数并有返回值的方法:If you need to declare a method with parameters and return values, the method will look this:
1 2 3 4 5 6 7 | class TodoManager { func printWelcomeMessage(name:String) -> Int { println("Welcome to \(name)'s ToDo List") return 10 } } |
->操作符指向了返回类型 (真形象)The syntax looks a bit awkward especially for the -> operator. The above method takes a name parameter in String type as the input. The -> operator is used as an indicator for method with a return value. In the above code, you specify a return type of Int that returns the total number of todo items. Below demonstrates how you call the method:
1 2 3 | var todoManager = TodoManager() let numberOfTodoItem = todoManager.printWelcomeMessage("Simon") println(numberOfTodoItem) |
流程控制Control Flow
流程控制和循环是和大多数一样,类C,经典之作。下面是switch的用法Control flow and loops employ a very C-like syntax. As you can see above, Swift provides for-in loop to iterate through arrays and dictionaries. You can use if statement to execute code based on a certain condition. Here I’d just like to highlight the switch statement in Swift which is much powerful than that in Objective C. Take a look at the following sample switch statement. Do you notice anything special?
1 2 3 4 5 6 7 8 9 10 | switch recipeName { case "Egg Benedict": println("Let's cook!") case "Mushroom Risotto": println("Hmm... let me think about it") case "Hamburger": println("Love it!") default: println("Anything else") } |
Yes, switch statement can now handle strings. You can’t do switching on NSString in Objective C. You had to use several if statements to implement the above code. At last Swift brings us this most sought after utilization of switch statement.
switch还支持范围操作。Another enhancement of switch statement is the support of range matching. Take a look at the below code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | var speed = 50 switch speed { case 0: println("stop") case 0...40: println("slow") case 41...70: println("normal") case 71..101: println("fast") default: println("not classified yet") } // as the speed falls within the range of 41 and 70, it'll print normal to console |
The switch cases now lets you check values within a certain range by using two new operators: “…” and “..”. Both operators serve as a shortcut for expressing a range of values.
2种范围操作符的区别是 41...70 包括 41和70 ,41..70 包括的是41和69。Consider the sample range of “41…70″, the … operator defines a range that runs from 41 to 70, including both 41 and 70. If we use the .. operator instead of … in the example, this defines a range that runs from 41 to 69. In other words, 70 is excluded from the range.
有了swift还需要学习Objective C吗?Should I Still Learn Objective C?
答案是肯定的,当然不能一味的看未来,畅想swift一定会取代Oc,事实在做若干年的时间内,这还无法实现,Oc有大量成熟的案例项目和框架,swift从头搞这些需要时间,放弃Oc已有的东西也不现实。而且swift的定位也或为可知,谁知道它以后是不是下一个lua。而目前来看Oc作为IOS的绝对主力支撑还要继续维持很长时间。去Oc化,也要看IOS的态度。所以努力学好Oc对IOS的开发还是大有益处。坚持两手抓,两手都要硬,肯定是没错的。I hope this short tutorial gives you a very brief introduction of Swift. This is just the beginning of the Swift tutorials. We’ll continue to explore the language and share anything new with you. Of course, we’ll develop more detailed tutorials when Apple officially releases Xcode 6 and iOS 8 this fall. Meanwhile, if you want to further study the language, grab the free Swift book from iBooks Store.
Before I end this post, I’d like to take this chance to answer a common question after the announcement of Swift.
Should I continue to learn Objective C?
My view on Swift is it is the future of programming for iOS. Apple will continue to promote and add features to the language. As you can see in this tutorial, the syntax is more developer-friendly and it’s easier for beginner to learn, particular for those who have scripting background. It will definitely encourage more people to learn iOS programming and build iOS apps. That said, I think Objective C will not disappear overnight and is here to stay for years. There are tons of apps and code libraries that are written in Objective C. It’ll take time for developers to convert the code to Swift. As Xcode supports both Objective C and Swift, some developers may even keep the existing code in Objective C and only develop new library/app in Swift. Thus, I suggest you to learn both languages. If you can manage the fundamentals of Objective C, it’ll be very easy for you to switch over to Swift as the two languages are quite similar. And it would definitely give you an edge over other Swift-only developers in the market.