Swift and Objective-c syntax reference

Source: Internet
Author: User
Tags switch case

Swift and Objective-c syntax reference

Swift has been available for a while. Today we will summarize the differences between the syntax of Swift and Objective-c (hereinafter referred to as OC.

1. constants and variables:

Defining constants and variables in Swift is simple. constants use the let keyword and variables use the var keyword.

?var numberOfRows = 30let maxNumberOfRows = 100

When declaring a variable in OC, We need to specify the Data Type:

const int count = 10;double price = 23.55;NSString *myMessage = @"Objective-C is not dead yet!";

But we don't need it in Swift. Although Swift is a strong type language, it can deduce the type based on the Value assignment:

Et count = 10 // count will be recognized as Intvar price = 23.55 // price will be recognized as Doublevar myMessage = "Swift is the future! "// MyMessage will be recognized as String

Of course, writing variable names in Swift will not cause any problems:

var myMessage : String = "Swift is the future!"

2. There is no need to write a semicolon in Swift!

In OC, you need to write ";" next to each sentence to end the expression. Otherwise, an error will be reported. In Swift, you do not need to write a semicolon. Of course, there is no problem with writing it.

var myMessage = "No semicolon is needed"

3. String

In Swift, the String type is String, whether you define a constant String or a variable String.

?let dontModifyMe = "You cannot modify this string"var modifyMe = "You can modify this string"

In OC, you need to use NSString and NSMutableString to identify whether the string can be modified.

It is very convenient to connect two strings in Swift to form a new string. Use "+ ":

let firstMessage = "Swift is awesome. "let secondMessage= "What do you think?"var message = firstMessage + secondMessageprintln(message)

Println is a global printing method in Swift.

In OC, we use the stringWithFormat method:

NSString *firstMessage = @"Swift is awesome. ";NSString *secondMessage = @"What do you think?";NSString *message = [NSString stringWithFormat:@"%@%@", firstMessage, secondMessage];NSLog(@"%@", message);

To determine whether two strings are the same in OC, you cannot use "=". You need to use the isEqualToString method, however, in Swift, you can use "=" to determine whether the strings are the same.

? Var string1 = "Hello" var string2 = "Hello"
if string1 == string2 {    println("Both are the same")} 


4. Array

Array usage: Swift is similar to OC. Let's look at the example:

In OC:

?NSArray *recipes = @[@"Egg Benedict", @"Mushroom Risotto", @"Full Breakfast", @"Hamburger",@"Ham and Egg Sandwich"];

In Swift:

?var recipes = ["Egg Benedict", "Mushroom Risotto", "Full Breakfast", "Hamburger", "Ham and EggSandwich"]

You can insert any type of parameters to NSArray and NSMutableArray in OC, but only the same parameters can be inserted in OC.

Similar to NSArray, arrays in Swift also have many methods. For example, the count method returns the number of elements in the Array:

? Var recipes: [String] = ["Egg Benedict", "Mushroom Risotto", "Full Breakfast", "Hamburger", "Ham and Egg Sandwich"]
?var numberOfItems = recipes.count// recipes.count will return 5

In OC, you use the method addObject in NSMutableArray to add elements in the array. The method in Swift is simpler. You can use "+ =", for example:

recipes += ["Thai Shrimp Cake"]
Note that this method is used between arrays. If a single element is to be added to an array, add [] to the element.

To retrieve or replace the elements in the array and use the index, this is the same as in OC:

?var recipeItem = recipes[0]recipes[1] = "Cupcake"

In Swift, Range can be used to indicate the Range: for example
recipes[1...3] = ["Cheese Cake", "Greek Salad", "Braised Beef Cheeks"]
Here, the second to fourth elements in the recipes are replaced.

5. Dictionary

A dictionary is a collection type consisting of key-value pairs. This is similar to NSDictionary in OC. See the example below:

OC:

?NSDictionary *companies = @{@"AAPL" : @"Apple Inc", @"GOOG" : @"Google Inc", @"AMZN" :@"Amazon.com, Inc", @"FB" : @"Facebook Inc"};

Swift:

?var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc","FB" : "Facebook Inc"]
You can also declare its dictionary type:

?var companies: Dictionary
   
     = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc","AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]
   

To traverse a dictionary, you need to use tuples to save the information in the dictionary of each loop:

for (stockCode, name) in companies {    println("\(stockCode) = \(name)")}

You can also traverse the keys or values in the dictionary separately:

for stockCode in companies.keys {    println("Stock code = \(stockCode)")}for name in companies.values {    println("Company name = \(name)")}

To add a new key-value pair to the dictionary, use the following statement:

companies["TWTR"] = "Twitter Inc"

6. Class

If you create a class in OC, you will get two files, one interface file (. h file) and one implementation file (. m file ).

The class generated in Swift has only one file. swift file.

Example:

class Recipe {    var name: String = ""    var duration: Int = 10    var ingredients: [String] = ["egg"]}

In the above example, we created a Recipe class, which has three attributes, declared types, and initialized. During class initialization in Swift, its attributes must be initialized. If you do not want to set the default value of a property, use? Add it to the optional chain:

class Recipe {    var name: String?    var duration: Int = 10    var ingredients: [String]?}
In this way, when you create a class instance:

var recipeItem = Recipe()

The initial value of the attributes in these optional links is nil. You can assign values to them:

recipeItem.name = "Mushroom Risotto"recipeItem.duration = 30recipeItem.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 vegetablestock", "salt and pepper", "25g/1oz butter"]

Class can inherit the parent class and abide by the protocol, for example:

OC:

?@interface SimpleTableViewController : UIViewController 
   

Swift:

class SimpleTableViewController : UIViewController, UITableViewDelegate, UITableViewDataSource

7. Methods Method

Swift allows you to create methods in classes, struct, and enumeration.

The following is a method without parameters or return values:

class TodoManager {    func printWelcomeMessage() {        println("Welcome to My ToDo List")    }}

The format for calling a method in OC is as follows:

todoManager printWelcomeMessage];

The format for calling a method in Swift is as follows:

todoManager.printWelcomeMessage()

To create a method with parameters and return values, the format is as follows:

class TodoManager {    func printWelcomeMessage(name:String) -> Int {        println("Welcome to \(name)'s ToDo List")return 10 }}

"->" Indicates the return value type of the method.

You can call the above method as follows:

var todoManager = TodoManager()let numberOfTodoItem = todoManager.printWelcomeMessage("Simon")println(numberOfTodoItem)


8. Control Flow

The control flow and loop in Swift are quite in the C language style.

8.1for Loop

The for loop uses the for-in structure and can be used with Range (... Or... <:

for i in 0..<5 {    println("index = \(i)")}

Will be output in the console:

Index = 0

Index = 1

Index = 2

Index = 3

Index = 4



If we use a closed set..., the result will be returned:

Index = 0

Index = 1

Index = 2

Index = 3

Index = 4

Index = 5

If you want to use the structure in c, it is also possible:

for var i = 0; i < 5; i++ {    println("index = \(i)")}

But for does not need to be followed by parentheses.


8.2 if-else Structure

Similar to OC, but Swift is simpler. Condition statements do not need to be written in brackets:

var bookPrice = 1000;if bookPrice >= 999 {    println("Hey, the book is expensive")} else {    println("Okay, I can affort it")}

8.3 switch structure

The Switch structure in the switch has very powerful functions.

Example:

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")

First, switch in Swift can control strings. NSString in OC cannot be controlled by switch. to implement similar functions in OC, you can only use if-else.

In addition, you can see that we did not write a break in each case. In OC, you must write a break in each case. Otherwise, the next case will be entered after the current case ends, after the current case in Swift is executed, the switch automatically jumps out. If you need to enter the next case, add the fallthrough statement.

Finally, the switch case can contain the Range operation:

var speed = 50switch 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")}

9. Tuple tuples

Tuples are not available in OC. They can contain many different data types. You can use them as the return values of methods, in this way, a single tuple can be used to return a complex object. For example:

let company = ("AAPL", "Apple Inc", 93.5)

You can obtain the values in the tuples 'Company '. The usage is as follows:

let (stockCode, companyName, stockPrice) = companyprintln("stock code = \(stockCode)")println("company name = \(companyName)")println("stock price = \(stockPrice)")

Or company.0 or company.1 can also get the value. A better way is to give each element a name when defining the tuples:

let product = (id: "AP234", name: "iPhone 6", price: 599)println("id = \(product.id)")println("name = \(product.name)")println("price = USD\(product.price)")

The following is an example of using tuples as the return type:

Class Store {func getProduct (number: Int)-> (id: String, name: String, price: Int) {var id = "IP435", name = "iMac ", price = 1399 switch number {case 1: id = "AP234" name = "iPhone 6" price = 599 case 2: id = "PE645" name = "iPad Air" price = 499 default: break}
        return (id, name, price)    }}

Call:

let store = Store()let product = store.getProduct(2)println("id = \(product.id)")println("name = \(product.name)")println("price = USD\(product.price)")

10. Optional type

10.1 optional

The optional type is usually used in variables. The default value of the optional type is nil. If you assign a value to a non-selectable variable nil, an error is returned:

?var message: String = "Swift is awesome!" // OKmessage = nil // compile-time error

When not all attributes in your class are initialized, an error is returned:

class Messenger {    var message1: String = "Swift is awesome!" // OK    var message2: String // compile-time error}

In OC, When you assign a value to the variable nil or do not initialize the attribute, you will not receive a compilation error:

NSString *message = @"Objective-C will never die!";message = nil;class Messenger {    NSString *message1 = @"Objective will never die!";    NSString *message2;}

However, this does not mean that you cannot use attributes without initialization in Swift. Can we use them? To indicate that this is an optional variable:

class Messenger {    var message1: String = "Swift is awesome!" // OK    var message2: String? // OK}

10.2 why should we use an optional model?

There are many security considerations when designing the Swift language. The optional type indicates that Swift is a type of secure language, from the above example, you can see that the optional type in Swift will check some possible errors at runtime during compilation.

Consider the following methods in OC:

- (NSString *)findStockCode:(NSString *)company {    if ([company isEqualToString:@"Apple"]) {        return @"AAPL";    } else if ([company isEqualToString:@"Google"]) {        return @"GOOG";    }return nil; }

This method is used to determine whether the input string is Apple or Google. If it is other strings, nil is returned.

Suppose we define this method in the class and use it in the class:

NSString * stockCode = [self findStockCode: @ "Facebook"]; // nil is returned
?NSString *text = @"Stock Code - ";NSString *message = [text stringByAppendingString:stockCode]; // runtime errorNSLog(@"%@", message);

This code can be compiled, but an error occurs during running. The reason is that nil is returned when FaceBook is passed in to the method.

The above OC code is written in Swift as follows:

Func findStockCode (company: String)-> String? {If (company = "Apple") {return "AAPL"} else if (company = "Google") {return "GOOG"} return nil}
var stockCode:String? = findStockCode("Facebook")let text = "Stock Code - "let message = text + stockCode  // compile-time errorprintln(message)


This Code cannot be compiled to avoid running errors. Obviously, optional applications can improve the quality of code.

10.3 Option

We have seen the usage of the optional type above. How can we determine whether the value of an optional type variable is nil?

Example:

var stockCode:String? = findStockCode("Facebook")let text = "Stock Code - "if stockCode != nil {    let message = text + stockCode!    println(message)}

Similar to the pairing in OC, we use the if judgment statement to determine the null value of the optional type. Once we know that the optional type must have a value, we can use forced unblocking (or unpackage), that is, add an exclamation point after the variable name to get the value of the variable.

What if we forget to make a null value? You have forced unblocking, so no compilation error will occur.

var stockCode:String? = findStockCode("Facebook")let text = "Stock Code - "let message = text + stockCode!  // runtime error

A running error occurs. The error prompt is:

Can't unwrap Optional. None


10.4 binding optional

In addition to forcible unblocking, it is simpler and better to bind options. You can use the optional binding of the if-let structure to determine whether a variable is null.

Example:

var stockCode:String? = findStockCode("Facebook")let text = "Stock Code - "if let tempStockCode = stockCode {    let message = text + tempStockCode    println(message)}

If let means that if stockCode has a value, unpack it and assign it to a temporary variable tempStockCode, and execute the Code in the following braces (condition block, otherwise, the code in braces is skipped.

Because tempStockCode is a new constant, you don't have to use it any more! To obtain its value.

You can simplify this process:

let text = "Stock Code - "if var stockCode = findStockCode("Apple") {    let message = text + stockCode    println(message)}

We put the definition of stockCode in if, where stockCode is not an optional type, so we do not need to use it in the braces below! If it is nil, the code in braces will not be executed.

10.5 optional chain

We have a class Code with two attributes: code and price. Their types are optional. Change the return value of the stockCode method in the preceding example from String to return a Code type.

class Stock {    var code: String?    var price: Double?}func findStockCode(company: String) -> Stock? {    if (company == "Apple") {        let aapl: Stock = Stock()        aapl.code = "AAPL"        aapl.price = 90.32return aapl    } else if (company == "Google") {        let goog: Stock = Stock()        goog.code = "GOOG"        goog.price = 556.36return goog }return nil }

Now we calculate how much it costs to buy 100 Apple:

if let stock = findStockCode("Apple") {    if let sharePrice = stock.price {        let totalCost = sharePrice * 100        println(totalCost)    }}

Because the findStockCode return value is an optional value, we use the optional binding to determine, but the price attribute of Stock is also optional, so we use an optional binding to determine the null value.

There is no problem with the code above. if let is not needed, we have a simpler method. You can change the code above to an optional link operation. Does this feature allow us to use multiple optional types? Connection:

if let sharePrice = findStockCode("Apple")?.price {    let totalCost = sharePrice * 100    println(totalCost)}





Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.