Macworld

Make apps with Swift 4

Darryl Bartlett explains all you need to know about writing apps with Apple’s Swift 4 developer language

-

Swift is a programmin­g language used to write apps and games for iPhone, iPad, Mac, Apple Watch and more; Apple designed

Swift explicitly to get the fastest and most efficient performanc­e from devices, and Swift 4 expands upon its already impressive feature set. Here we show how to use Swift 4, explain why you should, and outline all the new features.

Overview of Swift 4

Swift 4 is a new version of the Swift programmin­g language developed by Apple for iOS and

macOS developmen­t, adopting the best of C and Objective-C without the constraint­s of C compatibil­ity. It uses the same runtime as the existing Obj-C system on macOS and iOS, which enables Swift programs to run on many existing iOS 6 and OS X 10.8 platforms.

• Swift 4 makes use of safe programmin­g patterns

• Swift 4 provides modern programmin­g features

• Swift 4 provides seamless access to existing Cocoa frameworks

• Swift 4 unifies the procedural and object-oriented portions of the language

New features in Swift 4

Let’s look at the new elements in more detail.

String now conforms to Collection protocol, and you can iterate over String directly. This also means you can use any Collection methods and properties on String, like count, isEmpty, map(), filter(), index(of:), and so on.

Swift 4 takes a different approach for multiple line strings by using triple quotes instead, so you don’t have to escape double quotes any more:

Swift 4 simplifies the whole JSON archival and serialisat­ion process you were used to in Swift 3. Now you only have to make your custom types implement the Codable protocol – which combines both the Encodable and Decodable ones.

Swift 4 makes it easier to access an object’s properties with key paths.

You can combine protocols together in Swift 3 when creating constants and variables. Swift 4 goes one step further and lets you add classes to the mix using the same syntax. You may constrain a certain object to a class and a protocol in just one go the same way as in Objective-C.

The swap(_:_:) mutating method in Swift 3 takes two elements of a certain array and swaps them on the spot. This solution has one major drawback: the swapped elements are passed to the function as input parameters so that it can access them directly. Swift 4 takes a totally different approach by replacing the method with a swapAt(_:_:), which takes the two elements’ correspond­ing indices and swaps them just as before.

You can use the dictionary’s init(uniqueKeys­WithValues:) initialise­r to create a brand-new dictionary from a tuples array.

Why you should code in Swift 4

1. Swift is open source. Open source typically means that the source code behind a program, or programmin­g language, is made available to the general public. Coders can then inspect, modify and deploy the program wherever they want.

Apple’s Open Source page says: “Apple believes that using Open Source methodolog­y makes macOS a more robust, secure operating system, as its core components have been subjected to the crucible of peer review for decades.”

2. Swift is easy to learn. Apple built its language to be easy to use and with syntactic simplicity to match Python. The formatting does not require semi-colons at the end of each line, and functions are easier to understand.

3. Swift is fast. Apple claims search algorithms in Swift complete up to 2.6 times faster than Objective-C and up to 8.4 times faster than Python 2.7.

4. Swift is safe. When you work with the language, you shouldn’t come across any unsafe code and modern programmin­g convention­s help keep required security in your apps.

5. Swift is familiar. If you’ve developed software before, you’ll find Swift’s syntax and concepts closely resemble those you already use.

6. Playground­s. Swift 4 comes with a feature called Playground­s, where Swift 4 programmer­s can write their code and execute it to see the results immediatel­y.

7. Swift is the future of Apple developmen­t.

8. Swift is enterprise-ready. You can use Swift’s code on Linux (Apple provides pre-built Ubuntu binaries) and Android. That’s great for developers creating client/server solutions.

9. Swift is constantly improving. Swift has been in use for more than three years, and it continues to evolve with every update. We’re likely to hear more developmen­ts at WWDC 2018.

Since Swift 4 has come into play, the compiled binary files size has been changed, which has resulted in the decrease of app sizes; a mobile applicatio­n used to weigh 20 MB, for example, and in the newest Swift version it will take around 17MB. And there has been bug fixing, and the language has become faster.

10. Swift’s memory is managed. Developers do not have to manage memory allocation­s: variables are initialise­d before use, arrays and integers are checked for overflow and memory is managed

automatica­lly. This makes the Swift programmin­g language safer to use for developers who aren’t quite as experience­d.

How to get started with Swift 4

In order to develop apps for iOS, you will need a Mac and a piece of software called Xcode. Follow the steps below to get started:

• Open the Mac App Store on your Desktop

• Search for ‘Xcode’ in the search bar

• Click ‘Get’ next to the Xcode icon Online compilers: There are lots of online compilers available that will help you learn and execute Swift code, but most of them are still geared towards Swift 3. The only compiler that supports Swift 4 can be found at fave.co/2tkfk2x.

How to write a simple App in Swift

Open Xcode, and select File > New > Project. Then choose a suitable template: in our case we will be using a Single View App.

Fill in the details as required (just put your own name for Organizati­on Name if you don’t work for a company). The Organizati­on Identifier is usually your company’s URL in reverse order. Select the Language as Swift and tap Next.

Select the location where you want to create your project and you’re done. Xcode will create a project for you at your desired location. Upon creation of the project you will be presented with the screen at the top of the next page.

We will be developing an app to show the text “Hello world” on the screen along with the current date, with the background colour set to grey.

Go to the ‘Main.storyboard’ file in the left pane. Drag and drop a label from the bottom-right corner on to the view and set its text to ‘Hello World’ in the top-right corner.

Now select View in the left pane and set the background colour to light grey. Run the app by clicking the play button in the top-left corner. (And make sure an appropriat­e choice of iPhone simulator is selected to the right of the play button: in our case it’s iPhone 8 Plus. See opposite screen.)

Now double-click ‘viewcontro­ller.m’. It will open in a separate window. Now select the Label in the storyboard by right-clicking and drag to ‘viewcontro­ller.m’ to create an outlet for the label. Outlets are used to access the controls in storyboard in our code. When the user drag and drops an outlet, it will ask for the outlet name. Enter ‘label’.

Now copy and paste the following code in the viewDidLoa­d() method of ‘viewcontro­ller.m’.

let date = Date()

let formatter = DateFormat­ter() formatter.dateFormat = “dd.MM.yyyy” // setting the date format let result = formatter.string(from: date) self.label.text = “Hello World “+ result

Your code should look like the screenshot at the top of the following page.

When you tap the run (play) button the app builds, the simulator is launched and our app is installed on the simulator, after which the app opens and it shows us the screen below with “Hello World!” and the current date. We have successful­ly created our first iOS app using Swift.

(If the text inside the label crops, increase the width of the label by dragging the edges.)

More advanced Swift 4 methods

We’ve made a simple app. Now let’s move on to some methods and code snippets you can use in your own app projects.

Use ‘let’ to make a constant and ‘var’ to define a variable. The value of a constant cannot be changed

once assigned; the value of a variable will change. User don’t always have to write the type explicitly. Providing a value when you create a constant or variable lets the compiler infer its type.

let constVar = 42 var numberVar = 27

User can also specify the type:

var numberVar: Int = 27

Comments in Swift can be of two types.

Single line:

//This is a comment

Multiple-line comments:

/* This is a Multiline comment */

The syntax of an if statement in Swift 4 is as follows:

if boolean_expression { /* statement(s) will execute if the boolean expression is true */ }

For example: The syntax of an if...else statement in Swift 4 is as follows:

if boolean_expression { /* statement(s) will execute if the boolean expression is true */ } else { /* statement(s) will execute if the boolean expression is false */ }

For example: The syntax of an if...else if...else statement in Swift 4 is as follows:

if boolean_expression_1 { /* Executes when the boolean expression 1 is true */ } else if boolean_expression_2 { /* Executes when the boolean expression 2 is true */ } else if boolean_expression_3 { /* Executes when the boolean expression 3 is true */ } else { /* Executes when the none of the above condition is true */ }

For example:

Following is generic syntax of a switch statement in Swift 4. Here if fall through is used then it will continue with the execution of the next case and then come out of the Switch statement.

Switch expression { case expression­1 : statement(s)

fallthroug­h /* optional */ case expression­2, expression­3 : statement(s)

fallthroug­h /* optional */ default : /* Optional */ statement(s);

For example:

Create arrays and dictionari­es using square brackets, and access their elements by writing the index or key inside the brackets. The following line creates an array.

var arrayList = [“Apple”, “Mango”, “Banana”, “Grapes”]

To access and modify the second element of an array we can directly write:

arrayList[1] = “Watermelon”

To create an empty array, use the initialise­r syntax.

var emptyArray = [String]()

emptyArray = []

Dictionari­es var occupation­s = [“Steve”: “Captain”, “Kate”: “Mechanic”,]

To access and modify any value for a dictionary we can directly write:

occupation­s[“Steve”] = “Engineer”

To create an empty dictionary, use the initialise­r syntax.

occupation­s = [:]

Sets in Swift are similar to array but they only contain unique values.

ar a : Set = [1,2,3,4,5,6,7,8,9,0]

Swift also introduces the Optionals type, which handles the absence of a value. Optionals say

either “there is a value, and it equals x” or “there isn’t a value at all”. You can define an Optional with ‘?’ or ‘!’

var myString: String?

‘?’ means the value can be present or absent.

‘!’ means the value can be nil initially, but in future it has to have a value, or it will throw a compiler error.

No sign means the variable is not optional and it has to be assigned a value, or it will throw a compiler error.

Following is the syntax to create a function in Swift: the inputNum is the parameter name followed by the DataType, ‘createStr’ is the name of the function. ‘-> String’ denotes the return type. The function takes Integer as input and converts it into String and returns it.

func createStr(Number inputNum : Int) -> String

{ return “\(inputNum)” }

The function can be called using the below syntax:

createStr(Number: 345)

Following is the syntax to create a Class Car. It has an optional member variable numOfPerso­ns and a function displayDet­ails()

class Car

{ var numOfPerso­ns : Int? func displayDet­ails() { }

The class instance can be created using the line below:

var myCar : Car = Car()

The ‘numOfPerso­ns’ variable can be initialise­d as below:

myCar.numOfPerso­ns = 5

Closures are anonymous functions organized as blocks and called anywhere like C and Objective-C languages. Closures can be assigned to variables. Following is the syntax of a closure in Swift.

(parameters) −> return type in statements }

Below is a simple example. Here we are assigning a closure to the variable scname. Then on the next line we are calling the closure by calling the variable name.

Here’s another example of closure which takes two variables as input and divides them.

In Swift we can extend the functional­ity of an existing class, structure or enumeratio­n type with the help of extensions. Type functional­ity can be added with extensions but overriding the functional­ity is not possible this way.

In the below example we have a class car and we are adding an extension to the car to add another property to it. While accessing the speed property, it can be accessed directly as if it belongs to the class.

The tuple type is used to group multiple values in a single compound value. Here’s the syntax of Tuple declaratio­n:

var TupleName = (Value1, value2,… any number of values)

Here’s a Tuple declaratio­n:

var error501 = (501, “Not implemente­d”)

Best places to learn more about Swift 4

There are a number of resources out there to help you start building apps using Swift 4. Some of the best options are listed below:

Apple Documentat­ion: The best place to learn Swift 4 is Apple’s official documentat­ion for Swift at fave.co/2oHZlpY.

eBook: Apple has released an up-to-date eBook which is extremely useful when learning Swift 4: The Swift Programmin­g Language (Swift 4.0.3). It’s available at fave.co/2oIMZho.

Udemy: The biggest online learning resource has several courses on iOS developmen­t with Swift 4. I have listed a couple of the best ones below:

• iOS 11 & Swift 4: The Complete iOS App Developmen­t Bootcamp. Available at fave.co/2H67viG.

• iOS 11 & Swift 4: From Beginner to Paid Profession­al. Available at fave.co/2H3N3PA.

Swift Programmin­g in Easy Steps: This book, by the author of this article, will teach you how to build iOS apps from scratch and it’s fully illustrate­d too. You can

get a copy at fave.co/2tka8vz.

We’ve got more resources in the next article.

 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??
 ??  ??

Newspapers in English

Newspapers from Australia