Tuesday, 27 December 2016

The Swift Programming Language: An Introduction

What is Swift?

In late 2014 Apple released a new programming language to create iOS and OS apps, this language is if you have not already guessed called Swift. Taken from Apple’s  own website:
Swift is an innovative new programming language for Cocoa and Cocoa Touch. Writing code is interactive and fun, the syntax is concise yet expressive, and apps run lightning-fast. Swift is ready for your next iOS and OS X project — or for addition into your current app — because Swift code works side-by-side with Objective-C.
Now, Apple have brought us Swift , the stronger, faster, smarter version of the Swift Programming Language.
“We’re stepping on the gas this year with Swift 2” said Apple’s Craig Federighi on stage at the 2015 WWDC keynote. “Swift 2.0 adds a bunch of features that developers have been asking for, to ensure that apps written in Swift are faster and can do more” 

Variables

Dynamic Variables

Variables in Swift 2 are a way for you to create dynamically assigned values. Dynamic means that the value you have set can change. To set a variable in Swift 2 you would prefix your variable name with the word var. This then tells Xcode that you are declaring a variable to use. The name for the variable that you set is a way for you to reference the value you want to set and use. The standard convention for declaring variables in Swift is to use camel case (Wikipedia) . Camel Case means that if you use several words to declare a variable, the first word will start with a lower case and the words after that will start with an uppercase.
Lets say you wanted to created a variable that would reference your age on Friday. You would do this like so:

var myAgeOnFriday
Finally, the next thing we need to do to this variable is to specify the value. So let’s say on Friday you’re going to be 23 you then need to add the following and you have successfully declared a variable called myAgeOnFriday with the value of 23.

var myAgeOnFriday : Int = 23
In the above Swift 2 Dynamic Variable declaration the equals operator = initializes the variable with that value.
To assign a String to the Dynamic Variable, You would do it like so:

var myName : String = "Mark"

Constant Variables

So we have covered how to create dynamic variables in Swift and how you can change them. But what if you wanted to use a variable that you knew was not going to change? For example the date you were born. For this we can use a constant. Declaring a constant in Swift is a little different than the usual variable declaration of var instead we use let. So to declare a constant in Swift we would write:

let dateOfBirth: Int = 12011988
Constants are only meant to be used with values that you are 100% sure will not change and if you tried to edit them later on you will get an error. So let’s say that we decided we were born on another day and wanted to change that constant after we have defined it like so:

dateOfBirth = 12021988
You will get this error: Cannot assign to ‘let’ value ‘dateOfBirth’. This is just Xcode saying that the value is set using let and that it is a constant that cannot be changed.

Type Annotation

Because Swift is a type safe language it’s better (best practice) to create an explicit variable. This means you tell Xcode what type of variable is going to be used. After the above declaration you would follow that with a colon : and then declare the variable type.
If you have a variable that is going to be an integer, like myAgeOnFriday you would write:

var myAgeOnFriday : Int
This is basically saying declare a variable called myAgeOnFriday of type integer.

Type Inference

So, the way that I have shown you so far is to declare your variable by giving it a name and then defining the type of variable: Int, String, Bool. However, This is only the best practice and you do not need to do this. Swift is clever enough to know what type of variable you are wanting to create just by the way you define the value (value is the assigned data at the right side of the equals sign). For example if you wrap the value in “value” double quotation marks then Swift will know that this value is a String. So using the above defined variables this is how you can define them without using the Swift explicit variable option:

// Declare an integer
var myAgeOnFriday = 23

// Declare a Boolean
var isUserLoggedIn = true

// Declare a String
var myStatusUpdate  = "Today I won £300"
As you can see, the colon and the declaration of type (Int,String,Boolean) is no longer required. This can save you a lot of time.

Variable Naming

A little bit above I mentioned the naming convention of Camel Case. Now, this is a naming convention, but you can actually name your variables anything, even using Unicode characters:

let π = 3.14159

let ?? = "dogcow"
As you can see in the above examples, we have not used Swift Type Annotation when declaring our variables. This is because you don’t have to. It’s just better practice to do so.

Swift String Mutability

This might sound weird or even scaring but it is nothing to worry about. I’m only adding this section in briefly as I’ve seen a lot of people refer to the term String Mutability. When I first started coding I was very unfamiliar with this. So Succinctly here is the Explanation taken from Apple [3]:
You indicate whether a particular String can be modified (or mutated) by assigning it to a variable (in which case it can be modified), or to a constant (in which case it cannot be modified which makes it immutable)

Integers

Integers in Swift are a whole number which can be positive or negative. As you can see in the above declaration you would initialise an integer in Swift with Int.

Floats

A Float is basically an integer with a decimal place in it, for example 1.23. Setting a float variable in Swift is pretty much the same as setting an integer however you use the word Float. Let’s say you had loan amount that you borrowed and you needed to set this at the top of the code. You would do this like so:

var myLoanAmount : Float = 3500.37

Strings

A String is a collection of ordered characters and can be made up of both integers and letters. For example you could have:

var myStatusUpdate: String = "Today I won £300"
You might see empty strings being declared in code and this is usually because the coder has wanted to define all the variables at the beginning so that its easier to add and append things to them. Here are some examples:

var emptyString = ""               // empty string literal
var anotherEmptyString = String()  // initializer syntax

String Concatenation in Swift

Concatenating strings is a way to join two or more strings together. This comes in very useful when you are gathering peoples names for example.
Let’s say that you have a variable called name:

var name = "iOS"
Which only has the first name but you want to assign a last name also. Because the variable as already been initialised you can simply just type the variable name and add it to itself.

name = name + " Blog"
// This now outputs 'iOS Blog'
Why would you do this? This might be very useful especially if you get the first name and the last name from different views and at different points throughout the application process.
You can also add two variables together like so:

var firstName = "iOS"
var lastName = " Blog"
var fullName = "" // Blank but initialised

fullName = firstName + lastName

// This outputs iOS Blog
You can also add in String variables and text and concatenate them together, like so:

var flowerColour = "red"
var flowerType = "Tulip"
var sentence = ""

sentence = "The " + flowerType + " was " + flowerColour + " and looked amazing"

// Outputs:
// The Tulip was red and looked amazing
If you wanted to add in any variable, integer or String into the ‘sentence‘ variable you can do so if you wrap it in \(variable). This is called Swift String interpolation and here is an example:

var myAge = 23
var event = "Party"
var sentence = ""

sentence = "Yesterday I was \(myAge) and I had an awesome \(event)"

// Outputs
// Yesterday I was 23 and I had an awesome Party
If you try to add an integer into the string variable above you will get an error. Let’s give it a go: If you replace \(myAge) in the above variable statement with ” + 23 + “ you will get this error: UInt8 is not convertible to String.

Capitalize Words in Strings

What is you wanted to display the first character of every word in a sentence with a capital letter? The Swift Programming Language gives us capitalizedString to do just that. You will need to declare a new variable and pass in the variable you want to capitalize with capitalizedString appended. Like so:

var originalString = "This is a sentence, thankfully."
let capitalizedString = originalString.capitalizedString

print(capitalizedString)
// Outputs: This Is A Sentence, Thankfully

Check if String is Empty

There might be a time, especially when you are validating form fields that you need to check whether a string is empty or not. Luckily, Swift gives us a nifty fix for this called: isEmpty. You need to add this as a condition in an if-else statement:

var yourString = "Hello World!"

if yourString.isEmpty {
    print("Oh dear, this string is empty")
}
else {
    print("Nope, it's not empty")
}

How to reverse Strings in Swift

Introducing swift reverse(). For a little bit of fun I will show you how to do this. I have not found a professional use for it yet, but you never know.

let str = "Hello, world!"
let reversed = String(str.characters.reverse())
print(reversed)

//Outputs !dlrow ,olleH
Quite fun, right?

How to trim Strings in Swift

What we mean by trimming a string in Swift is to remove the white space at the beginning or the end of the string. This might not seem useful but think about it, How many times have you tried to log into a website and kept getting an error, wrong username or password. Only to realize you have pressed the space-bar and added in a space which the system counted as a character? Now you see the important.
So here is how we trim white space in Swift:

var username = "  userName01     "
username  = username.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())

print(username)
Pretty useful right? You will remember this one for a while. You’re Welcome.

How to get the length of a string in Swift

This is useful if you want to set a minimum length of a password for example. Swift gives us characters.count which will count all the characters, even white space:

let password = "my$uperSec3rP@asswrd"
let length = password.characters.count

print(length)
// Outputs: 20
You would use this with an If-Else Statement to check the length complies with your prerequisite.

Boolean

Booleans are a fantastic type of variable that you can set. This variable will return the value of either trueor false and to set it you use the Bool declaration after the colon in your variable, like so:

var isUserLoggedIn: Bool = true
As you can probably gather from the variable name set above a Booleanis a nifty way to assign a value that you can check against. So above the variable name is: isUserLoggedIn – We can perform a check on this using an if-statement (We will cover if-statements later on down the article) to see if the user is logged in. This is very handy to be able to show different views or options for users that are not logged in or those that are.

Swift Arrays

We know how to create a variable for a name, but lets assume that you are running a phone call tree and you have a list of 23 and growing names. Adding new lines for every single name is going to be tedious. So what is an Array? Well its basically a way to hold many variables in a specific order. An Array will assign each Value an index value. It’s important to know that the index values in Arrays start at 0.
Taking into account what I just mentioned that the list is for a phone call tree and that we do not know how many people will be in the list we can create an Array like so:

var phoneTreeNames: [String] = ["John","Laura","Chris","Dave","Liam","Joseph"]
As you can see, we have started with the declaration of a variable: var. and then specified the array name: phoneTreeNames and then the type inference of: String however we do not need to specify the type, just like we don’t when declaring variables in Swift.
As mentioned previously if you are wondering about the Mutability of Arrays then the rules specified above are exactly the same.
As mentioned at the beginning of the Array section each Value in the Array will have an automatic index value assigned to it. We can use this to get the item out of the array like so:

var phoneTreeNames: [String] = ["John","Laura","Chris","Dave","Liam","Joseph"]

print(phoneTreeNames[3])
// Outputs: Dave

Get the First and Last items in Array

The new update to the Swift Programming Language allows us to find the first and last items in an array by using, you guessed it first & last:

print(phoneTreeNames.first)
print(phoneTreeNames.last)
So, how many names are in this Array? If you need to get the total value of these arrays at any time you can call the count function. Like so:

print(phoneTreeNames.count)
//Outputs 6

// Or you could assign it to a variable
let totalInArray = phoneTreeNames.count
print(totalInArray)
//Outputs 6

Append items into Array

You can append items to the array using the append method, providing that it is mutable. This means that you have declared the array with var not let.
You can do this quite easily, like so:

phoneTreeNames.append("Simon")

Change items in the array

If you are wanting to change the name in an array, then you can modify it using the allocated array index value.
Let’s say you want to change the name Laura in the above array that we have been using, which is in the second position of the array but has an index value of 1. Remember I said that arrays start their index value at 0. You would do this like:

phoneTreeNames[1] = "Jeremy"
Goodbye Laura and Hello Jeremy, Snap!

Delete items from the array

Oh no, Jeremy has now decided to leave the phone tree and now you have to remove him from the list. No problem. Again, we will use the array index value but this time pass it as a parameter to the Swift removeAtIndex(*) Function:

phoneTreeNames.removeAtIndex(1)
All done. He has now been removed from the list.

Dictionaries

In Swift, you can store associates Key and Value data in dictionaries. A quick way to remember this is just think about a book. The table of contents is the key and the page is the value. Dictionaries do not sort or organise your data in any specific order and to get the Value you need to reference the Key. Let’s say that you have three children (Rich, John and Carl) and you want to store their ages (3,5,9) respectively. You would do this like:

var children : [String: Int] = ["Rich" : 3, "John": 5, "Carl": 9]
As you can see in the example above, We have declared a Dictionary by typing var children :. We have then declared the type inference for the Key as String and the Value as Integer: [String: Int] and then we have added the values: = [“Rich” : 3, “John”: 5, “Carl”: 9]. Each of the Keys (the names) have the corresponding value (their ages).

Access Value in Dictionary by Key

Ok, so now lets assume you forgot one of your child’s ages and you need to query that from the Swift Dictionary we talked about above. It’s pretty simple, providing you have not forgotten your child’s name also:

print(children ["John"])

//Outputs 5

Delete from Dictionary using Key

Now, we’re going to assume that the aforementioned child called John has been to much to handle and you have sold him for some bread, milk and fifty shillings and you need to remove him from the Dictionary, Although I don’t condone child sale I will show you how to remove an item from the dictionary by using the key:

children.removeValueForKey("John")

// Now view your remaining children 
print(children)

Remove all from dictionary in Swift

Ok, since the sale of John your other children have become unruly, so much so you’re sat there thinking about the days you wanted to travel, the days before the children. Well, the solution here is just to remove them all:

children.removeAll()

print(children)
And Voila, you’re free.

Swift Loops

Loops in Swift allow you to iterate over pieces of code and perform actions on them.

Swift For Loop

One of the more common loops in Swift is the For-Condition-Increment (‘For loop’ for short). This loop follows this format:

for (variable; condition; increment) { }
The variable is often an integer that is used to keep track of the current number of loops iterated. The condition is checked after each loop; if it is true, the loop runs again. If the condition is false, the loop will stop running. Last but not least is the increment which is the amount added to the variable every time the loop executes.
Take the following code:

for (var counter = 0; counter < 6; counter++) { 
    print("Looped")
}
The variable: counter is currently set to 0 and the condition is saying if the counter is less < than 6. The increment will add 1 to the value of counter $counter++.
So when you run this code it will run through like so:
- Get the value of var counter
- Check if counter is less then 6
- If value is less than 6, add 1 to the counter
- Repeat until counter is 6
Most increments are written using a common shorthand practice:counter++. Normally, to increment a variable by one, the syntax looks like this:

counter = counter + 1
This code takes the counter variable and sets it equal to the counter variable plus one. This increases the counter value by one each time it is executed. However you can use this shortcut in Swift. Adding ++ to the end of a variable name to increment it by one. For example:

counter++
This is exactly the same as:

counter = counter + 1
You can do a lot with counters, check out how to create a counter application with Swift NSTimer

Swift Repeat-While Loop

A Repeat-while loop is similar to a for loop in that it runs with a condition. Lets say you have a game, and for every player who's score was under the next level target, lets say 100, you could print a statement for everyone of them

var playerID = 0
repeat {
    print("The Next Level !waits!!")
    i++
}
while playerID < 100

Swift Guard Statement

Using if-let often you need to do a lot of work within the scope of the braces that follow the statement or pass a value back to another optional. With guard you deal with the else statement first for what happens if the statement fails, after which you have access to the value(s) in non-optional form.
Check out our introduction to Swift Guard statement for a more exhaustive explanation and implementation.

Swift Enums

An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code. As of Swift 2, the Swift Enums can now support multiple types and have some additions to Raw Values. Pretty swanky eh :)
Classes in Swift

Classes are general-purpose, flexible constructs that become the building blocks of your program's code. You define properties and methods to add functionality to your classes by using exactly the same syntax as for constantsvariables, and functions.
To define a class in Swift, we start with the declaration of Class followed by the name that we want to call it. In this example, We're going to call it Person. So, lets declare our first Class in Swift:

class Person { }
Unlike other programming languages, Swift does not require you to create separate interface and implementation files for custom classes and structures. In Swift, you define a class or a structure in a single file, and the external interface to that class or structure is automatically made available for other code to use. 

Class Properties

Just like most OOP (Object-Orientated Programming) Languages, Swift can have properties.
Properties associate values with a particular class, structure, or enumeration. Stored properties store constant and variable values as part of an instance, whereas computed properties calculate (rather than store) a value
Lets create some properties in Swift for a person called John Appleseed.

var firstName: String
var lastName: String
The above properties are also known as stored properties. Make sure these are in the Class declaration.
We can now call any of this like so:

let myPerson = Person()

print(myPerson.firstName)
print(myPerson.lastName)

Swift Class Initialization

In the above example, we declared two strings, This means the class must have values for those. If not we will get errors, so now we need to set an initializer:

init(firstName: String, lastName: String) {
        self.firstName = firstName
        self.lastName = lastName
    }
Now we can call it like so:

var myPerson= Person(firstName: "John", lastName: "Appleseed")
You could always use the ? operator after your variables to negate the need to use the initializer.

Class Methods

Methods, also known as functions are a way to add functionality to your Classes. The term method is usually used instead of function in the context of classes. Defining a method is almost identical to defining a function.
Now, I'm going to show you how to define a method, I will show you how to calculate someone age from their birth year:

func getAge(thisYear:Int, birthYear:Int)->Int {
    return thisYear-birthYear;
}
What this function will do is take two values, one for thisYear & birthYear. Then it will subtract (-) one from the other, the result will be their age. Simply adding this function will not do anything, we need to initialise the class first:

let userAge = Person();
Now, we can pass two values to the method and print out the result like this:

print(userAge.getAge(2016, birthYear:1988));
This will output 28.

Class Inheritance

In the Swift Programming language a class can inherit methods, properties & many other characteristics from another class. When one class inherits from another, the inheriting class is known as a subclass, and the class it inherits from is known as its superclassInheritance is a fundamental behavior that differentiates classes from other types in Swift.
Lets create a Parent Class. This is known as just a regular class until it inherited:

class Animal {
    func sayHello() {
       print("Hello")
    }
}
Now we will create a subclass called dog that will inherit Animal:

class Dog : Animal {

}

We now need to create a new Dog instance:


let myDog = Dog()
Finally, to access the methods in the parent class, we would simply write:

myDog.sayHello()

Objective-C Guide For Developers: Part 5

This article, part 5 covers:
Defining custom types
Constants and enumerations
Bitwise operators and bitmasks
Structures

Defining custom types

We have already seen in the previous parts of this guide that there are two kinds of types a variable can have in Objective-C: basic types, as we have seen in the first part of this guide or object types, coming from classes either defined in Apple frameworks or defined by us. We have spent the last issues seeing how to create and extend the latter, but what about basic types? Can we define them too? If so, why would this be useful since we already have classes?
It turns out, of course, that we can indeed define new basic types, and actually we have already met some of these newly defined types, although I didn’t mention what they were. The C language basically offers only basic types for integers and floating point values. As we have seen, even the bool and char types are in the end just integers used in a different manner (and with a different byte size in memory, to be precise).
C, unlikely other languages like Java, allows also the definition of new basic types, the only condition being that these new types must be derived from the ones already provided by the language (or by composing them, as we will see later). In fact, the Objective-C basic types we encountered, like NSInteger or CGFloat, are just redefinitions of basic C types, namely long and double, respectively.
Why this redefinition? Could we not just use long and double instead? Of course we could, but there are some advantages in defining new types. The first one is clarity and legibility. CGFloat is not the only redefinition of the doubletype, there are also others, like NSTimeInterval. Despite being both the same type of value in memory, in our code we can clearly see that a variable of the first type represents graphical values, like coordinates on screen or sizes of graphical objects, while a variable of the second type represent an amount of time (in seconds, as defined by the documentation).
The other reason is one we already encountered, which is to differentiate the actual memory representation of a type based on the architecture in a way that is transparent to the developer. I said that a CGFloat is just a double, but actually that is not entirely correct: it’s a double on 64 bits architectures, while it’s a float on 32 bits ones. This redefinition allows the redefinition of the underlying representation of the types when needed, without requiring to change all the code that has been written up to that point (and this is exactly what happened to NSInteger and CGFloat in the transition from 32 to 64 bits architectures).
Now that we know the reasons to define new types, here is how to do it:
typedef existingType newType;
So, for example, if I want to define a type to represent people’s age as a positive integer, I can write:
typedef unsigned int Age;
or alternatively:
typedef NSUInteger Age;
I can then use this new type normally to define variables or properties in objects. Let’s rewrite our previous example of the Person class to include an age property:
typedef unsigned int Age;

@interface Person : NSObject

@property NSString *firstName;
@property NSString *lastName;
@property Age age;

@end

Constants and enumerations

Sometimes we need variables to be constant and to not change their value over time. This is easily done with the constkeyword in front of a variable declaration:
const double Pi = 3.14159;
The compiler will make sure that the content of this variable is never changed and will emit an error if you try to assign a new value to it after this declaration.
(By the way, if you need pi it’s already defined as the M_PI constant, together with other common mathematical constants in the header file math.h, which is always available in C, so you don’t have to include it directly in your source files).
Sometimes though we need to define more constants to enumerate different options we might have and we don’t really care about the values these constants might have as long as they are different from each other (sometimes we might need these values to be ordered).
Let’s say we want to add a sex property to our Person class. The only values we want to allow are Male, Female and Undefined when sex is not specified (for simplicity of the example I will not include the various transgender identities, but when you deal with such kind of data in real like it’s helpful to not make the assumption that people only identify themselves with the two canonical sexes).
We could already use the const keyword for this and define each sex as an integer constant with values 0, 1 and 2. This would work but would be impractical for larger sets of constants, because when we needed to introduce a new value inside the order, we will have to change all the other values manuallyt. Luckily C has a special construct made for this, called enum, which stands for enumeration:
enum {
    FirstConstant,
    SecondConstant,
    ...
    LastConstant
};
In this way all the constants get consecutive values starting from 0. Notice that the last constant does not have a comma after it and there is a semicolon after the closing brace (these are two common mistakes that cause syntax errors). It’s also possible to start from a value different than 0:
enum {
    FirstConstant = number,
    SecondConstant,
    ...
    LastConstant
};
The consecutive constants will get incremental values starting from the selected number. It is even possible to assign an arbitrary value to each constant, if needed.
It does not stop here. It’s possible to use an enumeration to define a new type:
typedef enum {
    FirstConstant,
    SecondConstant,
    ...
    LastConstant
} TypeName;
Where the name of the type goes at the end, after the closing brace. Since iOS 6 and Mac OS 10.8, Apple introduces a new NS_ENUM macro, which is now the preferred way to define enumerations. I included the other ways in this guide for completeness, since you might still find them in some code bases or in Apple documentation, but you should use NS_ENUM for your enumerations:
typedef NS_ENUM(baseType, newTypeName) {
    FirstConstant,
    SecondConstant,
    ...
    LastConstant
};
This macro adds a baseType to ensure a fixed size for the newly defined type. It  also provides hints to the compiler for type-checking and switch statement completeness. It’s also a bit more readable since the new type name is at the top and not at the bottom.
We can now expand our Person class to include sex:
typedef unsigned int Age;

typedef NS_ENUM(NSUInteger, Sex) {
    Undefined,
    Male,
    Female
};

@interface Person : NSObject

@property NSString *firstName;
@property NSString *lastName;
@property Age age;
@property Sex sex;

@end
I put the Undefined constant at the beginning, so it will have a value of 0 which is the default value properties have when an object is created. We can then use the constants when creating our object:
Person *person = [Person new];
person.firstName = @“Matteo”;
person.lastName = @“Manferdini”;
person.age = 33;
person.sex = Male;
Pay attention though that the compiler does not enforce the values that we can assign to a variable with an enumeration type. So this will still compile and run perfectly fine:
person.sex = 7;
Apple makes extensive uses of enumerations in its classes. For example, to create a new button in iOS 7, you would use the +buttonWithType: factory method with a UIButtonTypeSystem type:
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];

Bitwise operators and bitmasks

There is still a class of operators I didn’t mention over when I spoke about operators in Objective-C: bitwise operators. They are used for bitwise operations as the name implies, which are usually needed for some low level implementations (like network protocols), but can be used also for other purposes as we will now see. Like the other operators, these ones come directly from C. This is a table summing them up:

Operator  Description       Syntax

&   bitwise and       a & b
|    bitwise or       a | b
^    bitwise xor       a ^ b
<<    left shift       a << b
>>    right shift       a >> b
~    bitwise not, or one’s complement    ~a
Let’s see how they are usually used in Objective-C. With enumerations we have seen how we can create types that allow us to name different constants in a more readable way. The limitation with enumerations, though, is that a variable can only have one of the defined values at a time. What if we want to have a predefined set of options that are not mutually exclusive but can be set at the same time?
One way of doing this would be again to create a class with a boolean property for each option we want to enable simultaneously, but this would be an overkill and we would need to then assign or check every property singularly, making it very tedious to check all the options.
This special case can be handled easily with bitwise operators. We can make each constant in the enumeration have only one bit set to 1 and all others set to 0 (remember that we can assign an arbitrary value to an enumeration). Then, to specify multiple options at the same time we can use the bitwise or operator to group them in the same variable. Lets see how this works with an example.
Let’s say we want to have 4 non mutually exclusive options. We can declare an enumeration with bitmasks using the left shift operator. As we had the NS_ENUM macro for normal enumerations, we have the NS_OPTIONS macro for bitmask enumerations (but a simple typedef enum would still work, of course):
typedef NS_OPTIONS(NSUInteger, Options) {
    NoOptions = 0,
    Option1 =   1 << 0,
    Option2 =   1 << 1,
    Option3 =   1 << 2,
    Option4 =   1 << 3,
} Options;
The options will have the following bit representations in memory (I will omit leading zeros for clarity and only show the last 4 bits):
Option      Value

NoOptions   0000
Option1     0001
Option2     0010
Option3     0100
Option4     1000
When we want to group multiple options in the same variable, we can use the bitwise or operator:
Options enabledOptions = Option1 | Option3;
This groups the multiple options together in this way:
Option1          0001
Option3          0100
                 ----
enabledOptions   0101
As you can see, both the first and the third bit (from the right) are set in the enabledOptions variable, thus containing both values. To check wether any option is enabled we can use the bitwise and operator:
if (enabledOptions & Option1) {
    ...
}
If an option is enabled, operating a bitwise and on the value will produce a non zero value, that can be used as a true value in a condition. A bitwise and with a non enabled option produces a value of zero, which is equivalent to false.
You can use this in your code and Apple indeed does use it in different places. If we want to specify, for example, an autoresizing mask for a view with both flexible width and height, we can do it this way:
UIView *view = [[UIView alloc] initWithFrame:CGRectZero];
view.autoresizingMask = UIViewAutoresizingFlexibleWidth | 
                        UIViewAutoresizingFlexibleHeight;

Structures

Now, what if we want a variable to hold more than one value? One possibility is of course to create an object for that, as we have already seen, and in many languages this is the only option to achieve this purpose. But Objective-C inherits a feature from C that allows variables to contain more than one value, without being an object: structures.
You rarely need to create structures in your apps, but if you need something more lightweight than an object to contain simple values and with faster access a struct might be your tool. A structure is just a some space in memory that contains some values exactly as variables do, so it does not incur in the additional overhead of objects. A structure variable is declared with the keyword struct and can contain as many values as you want:
struct variableName {
    type memberName;
    ...
};
The syntax is similar to that of enumerations, but notice that here there is a semicolon after each member of the structure, because they act like variable declarations inside of the structure.
Let’s say, for example, that you want to store the value of a point on screen, which is identified by x and y coordinates. You can do so with a structure:
struct point {
    CGFloat x;
    CGFloat y;
};
You can then access the members with dot notation:
point.x = 100.0;
point.y = 200.0;
Or you can initialize the whole structure in one line using the following syntax with curly braces:
 point = {100.0, 200.0};
As happens for enumerations, you can turn structures into basic types to be able to reuse them:
typedef struct {
    type memberName;
    ...
} typeName;
This is exactly how the CGPoint type is declared, for example. CGPoint is used to store coordinates of graphical objects in iOS apps.
A disadvantage of structures over objects is that functionality needs to be defined externally. After all structures are only a basic type and cannot have methods attached. This requires you to write C functions to operate on them, which you usually don’t want to do. For example, CGPoint has a function to initialize a new structure:
CGPoint point = CGPointMake(100.0, 200.0);
or a function to compare two points:
if (CGPointEqualToPoint(point1, point2) {
    ...
}
Structures can also contain other structures, as in CGFrame, a type that indicated rectangles of graphical objects. A CGFrame has a origin, which is a CGPoint, and a size expressed in width and height, which is a CGSize. Under ARC, though, a structure cannot contain objects, so a structure can only be composed from other basic types.
These are structures you will encounter quite often, with other structures (like CGAffineTransform, for example, if you want to rotate, scale or translate graphical objects). There are a lot of functions in Apple frameworks to deal with these structures, but as you can see, this separates the functionality from the data, which defeats the Object Oriented Paradigm. For this reason it’s usually better to create a new class instead of a structure for your values, unless you have specific reasons like compatibility with C or C++ code, or to optimize execution speed.