Basic Swift Syntax

Calling Methods (Hello World) 

In Objective-C, to print “Hello World” on the console, you would use the NSLog() method:

NSLog(@"Hello World");

In Swift, the equivalent is as follows:

println("Hello World")

You should notice a couple of big differences:

  • No semicolons: Swift uses the newline character to separate lines.
  • No @ symbol: Swift has its own String class, which is implemented as a simple character array.
  • println: Swift uses this familiar method name from C and Java to allow you to print a line directly to the console.

Calling a method with multiple parameters in Objective-C looks like this:

NSInteger finalSum = [self calculateSumOf:5 andValue:5];

In Swift, you call methods with multiple parameters by adding them to a comma-delimited list within the parentheses (as you would in C or Java):

var finalSum = calculateSum(5, 5)

If the method defines labels for its parameters, add the labels in front of the values:

var finalSum = calculateSum(firstValue: 5, secondValue: 5)

Defining Variables

After “Hello World,” every programming lesson must continue with a discussion of variables.

In Objective-C, you created variables by declaring the type, variable, and value:

NSInteger count = 5;

In Swift, you declare variables by specifying their name and mutability (var or let), and optionally, the data type and initialization value:

var count : Int = 5

All variables defined with var in Swift are mutable, meaning you can change their values without re-initializing the variable—for example, NSMutableString or NSMutableArray.

The let keyword is similar to const in Objective-C and C; this is a constant value that is not meant to change.

Swift infers data types, so if you prefer, you can omit the type from your declaration:

var count = 5

Instantiating Objects

In Objective-C, you would instantiate an object by allocating it in memory and then calling its constructor method:

NSMutableArray *fileArray = [[NSMutableArray alloc] init];

Things are a bit easier in Swift. Swift automatically allocates memory, removing the allocstep. Additionally, the default constructor for a class in Swift is the class name with an empty set of parentheses appended to the end:

var fileArray = NSMutableArray()

If the class you are initializing takes parameters in its constructor, call the constructor as you would any other method:

var myView = UIView(frame: myFrame)

If you are instantiating an object from an Objective-C class, you need to call its constructor as a method:

var mutableArray = NSMutableArray()

Accessing Properties and Methods (Including Objective-C) 

In Swift, you can access a property or method of an object by using dot-notation, as you would in C or Java. This includes classes that were defined in Objective-C.

In Objective-C, you accessed the lastPathComponent property of a string by using the following code:

NSString *extension = [fileName lastPathComponent];

The Swift equivalent is as follows:

var extension = fileName.lastPathComponent

To call the reloadSubviews method on a UIView object in Objective-C, you would make a call like the following:

[myView reloadSubviews];

In Swift, the same line of code would look like this:

myView.reloadSubviews()

Casting

In Objective-C, to cast an object from one class to another, you would prepend the class name and optionally an asterisk, identifying your pointer:

UINavigationController *navigatonController = (UINavigationController *)segue.destinationController;

In Swift, casting is as easy as using the as keyword:

let navigationController = segue.destinationController as UINavigatonController

Simply add the as keyword and the class name to the result, and the compiler will do the rest for you. You can even insert this keyword inline, wherever you would normally use your object:

for (file as String in fileArray) {}

Using String Formatters

In Objective-C, when you wanted to insert a value from an object into a string, you had to use a string formatter to build a custom string:

NSString *summaryString = [NSString
    stringWithFormat:@"value 1: %d value 2: %d", value1, value2];

For each value you wanted to insert into the string, you needed to use a substitution character representing its type.

In Swift, this is a thing of the past. You can insert a value into a string by placing the variable’s name in parentheses, prepended by a forward slash:

let value1 = 5
let value2 = 10
var summaryString = "value 1: \(value1) value2: \(value2)"

Using Arrays

In Objective-C, you used the NSArray class to represent arrays. Arrays in Objective-C contained objects only, and could be initialized with several convenience constructor methods, including [NSArray arrayWithObjects:]:

NSArray *stringArray = [NSArray arrayWithObjects:@"string 1",
    @"string 2", @"string 3"]

In Swift, you can declare an array by providing its values in square brackets when you define the variable:

var stringArray = ["string 1", "string 2", "string 3"]

Swift does not place the same restriction on the contents of an array, so you can initialize it with scalar values (such as Ints):

var intArray = [1, 3, 5]

If you do not want to initialize your array with values, declare a variable type for the input by placing the type name in square brackets:

var intArray : [Int]

You can also use subscript notation to read or change values in a Swift array:

var sampleString = stringArray[3]

If you define your array as a mutable variable, you can use the plus (+) operator to append values to the array:

stringArray += "string4"

Using Conditional Logic 

In Objective-C, you implemented the most basic kind of conditional logic by placing a comparison in braces, as part of an if statement:

if (currentValue < maximumValue) {
}

In Swift, this syntax is largely unchanged, except the requirement for parentheses is gone:

if currentValue < maximumValue

An if-else statement retains this rule as well:

if currentValue < maximumValue {
    //Do something
} else if currentValue == 3 {
    //Do something else
}

Note  All the comparison operators you are familiar with from Objective-C are still valid in Swift.

When you wanted to check against multiple values in Objective-C, you used a switchstatement, with a case block for each value:

switch(currentValue) {
    case 1: NSLog("value 1");
        break;
    case 2: NSLog("value 2");
        break;
    case 3: NSLog("value 3");
        break;
}

The good news is the switch statement is also available in Swift, with a few changes:

  • switch statements in Swift allow you to compare objects. The Objective-C requirement for comparing only values has been eliminated in Swift.
  • switch statements in Swift no longer fall through by default. This means you do not have to add a break; statement at the end of each case.
  • switch statements in Swift need to be exhaustive (meaning they must either cover all values or include a default case). This requirement is a best practice for code security and prevents unexpected comparisons.

In Swift, the earlier switch statement would look like this:

switch currentValue {
    case 1: println("value 1")
    case 2: NSLog("value 2")
    case 3: NSLog("value 3")
    default: NSLog("other value")
}

Using Loops

The syntax for all of the major types of loops (forfor-eachdodo-while) are largely unchanged in Swift. Two major changes are that you do not need to declare your type, and parentheses are once again optional:

for name in nameArray {
    println("name = \(name)")
}

Swift includes a major addition that can improve your loops: ranges. Ranges in Swift allow you to specify a set of values that you can use to iterate a loop or as part of comparison.

There are two major types of ranges in Swift: 

  • Closed ranges, expressed as x...y, create a range that starts at x and includes all values including y. (Note: three dots!)
  • Half-open ranges, expressed as x..y , create a range that starts at x and includes all values up to y. (Note: two dots!)

You could use a range in a for-each loop as follows:

for i in 1..5  {
    println(i)
}

This would print the numbers 1–4.

Defining Methods

Before defining a method in Swift, let’s investigate a method signature in Objective-C:

-(BOOL)compareValue1:(NSInteger)value1 toValue2:(NSInteger)value2;

In this line of code, you can see that the return type comes before the method name and that each of the parameters is provided after a colon. You add labels to every parameter after the first one, to increase readability.

In Swift, you declare a method by placing the func keyword in front of the method name and then including the input parameters and output parameters in parentheses:

func compareValues(value1: Int, value2: Int) -> (result: Bool)

Swift uses -> to separate the input parameters and return parameters.

As with variables in Swift, you indicate the type of each parameter by appending the type name with a colon.

If your method does not return anything, you can omit the return parameters and ->:

func isValidName(name: String) {
}

Calling Enumerated Types 

In Swift, you can build an enumerated type by specifying its name, type, and values:

enum PlaybackStates : Int {
    case .Failed = -1, case .Loading, case .Success
}

Unlike Objective-C, to denote values in an enum, you need to place a period before the constant name. When comparing against an enum value, retain the period:

if playbackState == .Success {
    println("Success!")

Using Unusual Punctuation (Question Mark and Exclamation Mark Operators) 

For anyone coming from a C-based language, one of the most jarring aspects of Swift is how it uses the question mark and exclamation mark operators.

In Swift, the question mark operator (?) is used to denote an optional variable. An optional variable is one that can hold either a value or nil. You may be wondering why this is important. In other languages, an object can be nil, but a scalar variable (such as an int) always stores a value. Optional variables in Swift remove this restriction, allowing anything to store a nil value.

You declare a variable as optional by appending a question mark to the end of its type:

var myString : String?

This also applies if you are initializing an object with a value:

var myString : String? = "Ahmed is cool"

Because Swift infers variable types, optionals are extremely important when you need to pass an object (such as an NSError) by reference.

Note  You still use a question mark to denote a ternary operation in Swift.

The exclamation mark operator in Swift allows you to unwrap an optional variable. This is the equivalent of dereferencing a pointer in Objective-C or another C-based language. Unwrapping allows you to extract an optional variable’s properties (or nil if the variable has not been initialized).

To unwrap a variable, append an exclamation mark to the end of its variable name:

var errorString = error!.description

Caution  Do not omit the period after the exclamation mark in dot-notation. Both are required to unwrap a variable.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值