Unveiled at WWDC 2015, Swift 2.0 is an enhanced update with integrated functionalities of its previous version Swift 1.2, thereby providing broader platform for programmers for generating the code. The upgraded version of programming language has been designed more powerful and interfacing for the users.
SQL Database Design For Developers at php[tek] 2024
Swift 2.0: Apple’s Advanced Programming Platform for Developers
1. Swift 2.0: Apple’s Advanced
Programming Platform for Developers
Over the years, Apple has been devising various gadgets and methodologies for the
technology sector. Consequently, it has held the nerve of the market with its innovative
digital products and software. Further, the company has also been reinventing its products
with advanced features to make them more functional. The Swift 2.0 is one of the latest
instances in this regards.
Unveiled at WWDC 2015, Swift 2.0 is an enhanced update with integrated functionalities of
its previous version Swift 1.2, thereby providing broader platform for programmers for
generating the code. The upgraded version of programming language has been designed
more powerful and interfacing for the users.
2. Check out some of the embroiled specifications of the recently released
programming language which include:
Guard Keyword:
Apple introduced a new keyword guard in Swift 2.0 which enables early returns.
Further, it has been specifically designed to filter invalid parameters being passed to a
method; hence it becomes easy for everyone to understand when they see its ongoing
performance.
Any optional variable unwrapped by guard remains the same in scope after the completion of
its process. Meaning, an optional variable could be used ahead after checking its authenticity.
For checking any condition you could now use guard rather than using if. Check out the
following code snippet:
1
2
3
4
5
6
7
func saveInfo() {
guard name.characters.count > 0 else {
print(“You need to provide a name.”)
return
}
save(name)
}
Defer Keyword:
This is another keyword introduced to Swift 2.0 after guard. Its functionality is more like that
of finally keyword in try … catch block in many other modern programming languages.
However, defer also includes some other specified features.
Defer has been specialized to execute the block of code before the termination of current
scope. Hence, any block of code which used to be executed with the method finally, could
now be generated by using defer.
3. Check out the below example in this regards:
1
2
3
4
5
6
7
8
9
10
11
12
func writeData() {
let file = openFile()
defer { closeFile(file) }
let employeeInfo = fetchEmployeeInfo()
guard employeeInfo = empInfo else { return }
file.write(employeeInfo)
let departmentInfo = fetchDepartmentByEmployee(employeeInfo)
guard departmentInfo = deptInfo else { throw
DepartmentError.UnmappedEmployee }
file.write(departmentInfo)
}
Although, in the above code, defer has been mentioned at the beginning, but it will execute
before the method exit.
The closeFile() function in defer block executes even if any of the return statement is called
before the termination of method block. That means it does not identify the method end by
its scope end but identifies the same by control flow exit from method.
This is what defer is all about. Apparently, if you return from a method at the end or part way
through, or if you exit method by throwing an error, you could expect of a deferred work to
take place, which would not be seen in case of finally block. This is how defer embroils a bit
more than finally block.
Protocol Extension:
Despite based on the platform of object oriented programming, Swift 2.0 appears to be a
protocol oriented programming language, when it comes to its protocol extension.
The earlier versions of Swift used to have protocols as interfaces, which define the
properties and methods executed from class, struct, or enum. Whereas, you have the options
to extend protocols thereby adding default implementations for properties and methods in
Swift 2.0. Though, this feature was already available with classes and structs, but once added
with protocols makes better approach. While it may initially seem as a minor feature,
protocol-extensions tend to change the way of code generation.
4. The following lines of code explain the same.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
protocol Product {
var productId : String { get }
var name : String { get }
var price : Double { get }
var percentageDiscount : Double { get }
var isDiscountAvailable : Bool { get }
}
protocol Discountable {
var discount : Double { get }
}
extension Product where Self : Discountable {
var isDiscountAvailable : Bool { return true }
}
struct iPhone6 : Product, Discountable {
let productId : String
let name : String
let price : Double
let percentageDiscount : Double
let isDiscountAvailable : Bool
var discount : Double {
return ((price * percentageDiscount) / 100)
}
}
Two protocols have been created in the above block for product and discount calculation on
product. Further, a protocol extension has been used to define that if in case a struct, class or
enum implements both protocol product and discountable then the default value of
isDiscountAvailable property is always set to true. Hence, it could be very well seen that the
adding new protocol extensions make Swift 2.0 a protocol oriented programming language.
Error Handling With New Type ErrorType To Throw Everything:
Error handling is the common feature in all modern programming languages, and swift too is
not an exception. It uses enums for error types to assure that error catching is complete.
5. Consider example in action below:
1
2
3
4
enum AppError : ErrorType {
case UserError,
case NetworkError
}
Apart from the new error type, Swift 2.0 also introduced three of the five new keywords: do,
catch, try, throw and throws. Additionally, do in do…while is now replaced with repeat
keyword which is again replaced with try of try..catch. Consequently, one more new keyword
has been introduced for do of do…while replacement that is repeat and is sentenced to
repeat…while.
1
2
3
4
5
6
func performSignUp() throws -> Bool {
guard self.isNetworkReachable else { throw AppError.NetworkError }
guard self.signUpSuccessfull else { throw AppError.UserError }
return self.doSignUp()
}
In example above, the throws keyword is used in method signature that specifies that this
method may throw an error at runtime, and while on the other hand, the throw keyword is
used in method definition which throws error in a specified predefined condition.
This part of example only show that how we can manage to throw our own user defined
errors in Swift 2.0, but to handle or catch an error at runtime. Just take a look-
1
2
3
4
5
6
7
8
9
10
11
12
do {
guard self.performSignUp() else {
return
}
print(“Your are successfully signed up, thank you.”)
} catch AppError.NetworkError {
print(“We have faced some network related issue, please check your
internet connection, and try again later.”)
} catch AppError.UserError {
print(“Please verify your user details, and try again.”)
} catch {
print(“Something went wrong, while signing up.”)
}
To handle or catch an error we use do…catch statement in Swift 2.0. In addition, catch allows
specifying an error type to catch/handle. But jut hold on! Swift 2.0 also have one more
6. feature to describe a generic error which we may not specify at design time, but can be
identified at runtime. This is also known as exhaustive error handling in Swift.
Let’s see an example to understand this in detail :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
enum AppError : ErrorType {
case UserError,
case NetworkError,
case Undefined(String)
}
func performSignUp() throws -> Bool {
guard self.isNetworkReachable else { throw AppError.NetworkError }
guard self.signUpSuccessfull else { throw AppError.UserError }
guard self.password.character.count > 5 else { throw
AppError.Undefined(“There is problem with your password.”) }
return self.doSignUp()
}
let userInfo = try! performSignUp()
print(userInfo)
Using try! keyword specifies that the call cannot fail then whatever may be the reason. This is
a decision which needs to be taken on a case-by-case basis by the programmer.
So, try! keyword is the best to be used for indicating Swift that this call will not fail.
Automatically Synthesized Headers:
In objective-C, header files provide a list of functionality exposed by the class mentioning
about the available methods along with the parameters that they take, but with none of the
code.
Swift doesn’t have header files, which means you write all your code in a swift file, without
worrying about updating the header files. Instead, keyword like private is used to show how
methods should be exposed to the outside world. But in loosing header files, swift lost the
functionality of determining the functions included inside a class. So, to avoid going through
the whole file, just in case to know about the functions, Apple provided a solution for this
issue through Xcode. It is able to show the synthesized header files by scanning through code
and producing virtual header files that summarize the exposed methods with none of the
code, just like you see if you try to inspect any of the Apple’s own classes.
7. In order, to create a header file for swift class in Xcode 7, go to Navigate > Generate
Interface.
Availability Checking:
Before Swift 2.0 if checking of the version compatibility was used to check by generating a
code that determine the OS version like:
1
2
3
4
5
if
NSProcessInfo().isOperationSystemAtLeastVersion(NSOperationSystemVersio
n(majorVersion:9, minorVersion:0, patchVersion:0)) {
print(“Do you stuffs…”)
} else {
print(“Current system version is lower than iOS 9”)
}
This used to lead to a lot of problems at developer’s end, and required the developer to know
about the availability of the particular API on the least version specified in the app setting.
With Swift 2.0 and Xcode 7 Apple introduced API availability checking. If you set your app’s
deployment target to a lower iOS release than the base SDK, Xcode will automatically scan
every API you use to make sure it’s available in your lowest deployment target version. This
piece of information was there in Apple’s API headers since many years, but it’s now only
being exposed to the compiler. With this information compiler you could make sure that your
project doesn’t contain any code that can’t run because of missing APIs.
By default, Swift compiler will compare your actual usage against your minimum deployment
target and if it finds any unavailable API, then it will give you an error.
We can now check the version with available keyword in Swift 2.0, easily and there is no
need to remember the lengthy code just for checking OS version. Let’s see this with an
example below:
1
2
3
4
5
6
func performTask() {
guard #available(iOS 9, *) else {
return
}
// Do your stuff here…
}
In the code above #available will check whether, we are on iOS 9 or later, or any other
unknown platform like WatchOS– that’s the * at the end, and it’s required. But this will only
prevent a particular part of code in a function. But what if you want to prevent entire
function or class from a lower OS version?
8. Swift 2.0 has province for such scenarios too.
Now with Swift 2.0 we can mark a check on entire method or class
using @available keyword as shown in example below:
1
2
3
4
@available(iOS 9, *)
func iOS9Work() {
// do stuff
}
Renamed Syntax:
As mentioned earlier, with Swift 2.0 there are many things renamed in the syntax. The do…
while is now changed to repeat…while, println function is no more available from Swift 2.0
rather now its renamed to old simple print function with an addition of a default argument
set to true which indicates whether to print a new line or not. The Printable protocol is now
renamed to CustomStringConvertible.
To conclude, Apple with its iOS application development along with Mac OS brings in Swift
2.0 with wide range of features. Meanwhile available for developers, Apple confirms that
Swift 2.0 would be an easier programming platform for the programmers.