Friday, 22 August 2014

Swift is a new programming language for iOS and OS X app development. Nonetheless, many parts of Swift will be familiar from your experience of developing in C and Objective-C. 


Constants and Variables

Constants and variables associate a name (such as maximumNumberOfLoginAttempts or welcomeMessage) with a value of a particular type (such as the number 10 or the string "Hello"). The value of a constant cannot be changed once it is set, whereas a variable can be set to a different value in the future.



Declaring Constants and Variables

Constants and variables must be declared before they are used. You declare constants with the let keyword and variables with the var keyword. Here’s an example of how constants and variables can be used to track the number of login attempts a user has made:


  • let maximumNumberOfLoginAttempts = 10
  • var currentLoginAttempt = 0


Type Annotations

You can provide a type annotation when you declare a constant or variable, to be clear about the kind of values the constant or variable can store. Write a type annotation by placing a colon after the constant or variable name, followed by a space, followed by the name of the type to use.
This example provides a type annotation for a variable called welcomeMessage, to indicate that the variable can store String values:


  • var welcomeMessage: String

The colon in the declaration means “…of type…,” so the code above can be read as:
“Declare a variable called welcomeMessage that is of type String.”
The phrase “of type String” means “can store any String value.” Think of it as meaning “the type of thing” (or “the kind of thing”) that can be stored.
The welcomeMessage variable can now be set to any string value without error:


  • welcomeMessage = "Hello"

You can define multiple related variables of the same type on a single line, separated by commas, with a single type annotation after the final variable name:


var     red, green, blue   : Double 



Integers

Integers are whole numbers with no fractional component, such as 42 and -23. Integers are either signed (positive, zero, or negative) or unsigned (positive or zero).
Swift provides signed and unsigned integers in 8, 16, 32, and 64 bit forms. These integers follow a naming convention similar to C, in that an 8-bit unsigned integer is of type UInt8, and a 32-bit signed integer is of type Int32. Like all types in Swift, these integer types have capitalized names.


Integer Bounds

You can access the minimum and maximum values of each integer type with its min and max properties:
  • let minValue = UInt8.min // minValue is equal to 0, and is of type UInt8
  • let maxValue = UInt8.max // maxValue is equal to 255, and is of type UInt8
The values of these properties are of the appropriate-sized number type (such as UInt8 in the example above) and can therefore be used in expressions alongside other values of the same type.






Int

In most cases, you don’t need to pick a specific size of integer to use in your code. Swift provides an additional integer type, Int, which has the same size as the current platform’s native word size:
  • On a 32-bit platform, Int is the same size as Int32.
  • On a 64-bit platform, Int is the same size as Int64.
Unless you need to work with a specific size of integer, always use Int for integer values in your code. This aids code consistency and interoperability. Even on 32-bit platforms, Int can store any value between -2,147,483,648 and 2,147,483,647, and is large enough for many integer ranges.



UInt

Swift also provides an unsigned integer type, UInt, which has the same size as the current platform’s native word size:
  • On a 32-bit platform, UInt is the same size as UInt32.
  • On a 64-bit platform, UInt is the same size as UInt64



Floating-Point Numbers

Floating-point numbers are numbers with a fractional component, such as 3.14159, 0.1, and -273.15.
Floating-point types can represent a much wider range of values than integer types, and can store numbers that are much larger or smaller than can be stored in an Int. Swift provides two signed floating-point number types:
  • Double represents a 64-bit floating-point number. Use it when floating-point values must be very large or particularly precise.
  • Float represents a 32-bit floating-point number. Use it when floating-point values do not require 64-bit precision. 

Numeric Literals

Integer literals can be written as:
  • A decimal number, with no prefix
  • A binary number, with a 0b prefix
  • An octal number, with a 0o prefix
  • A hexadecimal number, with a 0x prefix
All of these integer literals have a decimal value of 17:


  • let decimalInteger = 17
  • let binaryInteger = 0b10001 // 17 in binary notation
  • let octalInteger = 0o21 // 17 in octal notation
  • let hexadecimalInteger = 0x11 // 17 in hexadecimal notation

Floating-point literals can be decimal (with no prefix), or hexadecimal (with a 0x prefix). They must always have a number (or hexadecimal number) on both sides of the decimal point. They can also have an optional exponent, indicated by an uppercase or lowercase e for decimal floats, or an uppercase or lowercase p for hexadecimal floats.



Tuples

Tuples group multiple values into a single compound value. The values within a tuple can be of any type and do not have to be of the same type as each other.
In this example, (404, "Not Found") is a tuple that describes an HTTP status code. An HTTP status code is a special value returned by a web server whenever you request a web page. A status code of 404 Not Found is returned if you request a webpage that doesn’t exist.


  • let http404Error = (404, "Not Found")
  • // http404Error is of type (Int, String), and equals (404, "Not Found")

The (404, "Not Found") tuple groups together an Int and a String to give the HTTP status code two separate values: a number and a human-readable description. It can be described as “a tuple of type (Int, String)”.
You can create tuples from any permutation of types, and they can contain as many different types as you like. There’s nothing stopping you from having a tuple of type (Int, Int, Int), or (String, Bool), or indeed any other permutation you require.
You can decompose a tuple’s contents into separate constants or variables, which you then access as usual:


  • let (statusCode, statusMessage) = http404Error
  • println("The status code is \(statusCode)")
  • // prints "The status code is 404"
  • println("The status message is \(statusMessage)")
  • // prints "The status message is Not Found"

If you only need some of the tuple’s values, ignore parts of the tuple with an underscore (_) when you decompose the tuple:


  • let (justTheStatusCode, _) = http404Error
  • println("The status code is \(justTheStatusCode)")
  • // prints "The status code is 404"

Alternatively, access the individual element values in a tuple using index numbers starting at zero:


  • println("The status code is \(http404Error.0)")
  • // prints "The status code is 404"
  • println("The status message is \(http404Error.1)")
  • // prints "The status message is Not Found"

You can name the individual elements in a tuple when the tuple is defined:


  • let http200Status = (statusCode: 200, description: "OK")

If you name the elements in a tuple, you can use the element names to access the values of those elements:


  • println("The status code is \(http200Status.statusCode)")
  • // prints "The status code is 200"
  • println("The status message is \(http200Status.description)")
  • // prints "The status message is OK"

Tuples are particularly useful as the return values of functions. A function that tries to retrieve a web page might return the (Int, String) tuple type to describe the success or failure of the page retrieval. By returning a tuple with two distinct values, each of a different type, the function provides more useful information about its outcome than if it could only return a single value of a single type. For more information, see Functions with Multiple Return Values.











No comments:

Post a Comment