Make apps with Swift 4

Dar­ryl Bartlett ex­plains all you need to know about writ­ing apps with Ap­ple’s Swift 4 de­vel­oper lan­guage

Macworld - - FEATURE -

Swift is a pro­gram­ming lan­guage used to write apps and games for iPhone, iPad, Mac, Ap­ple Watch and more; Ap­ple de­signed

Swift ex­plic­itly to get the fastest and most ef­fi­cient per­for­mance from de­vices, and Swift 4 ex­pands upon its al­ready im­pres­sive fea­ture set. Here we show how to use Swift 4, ex­plain why you should, and out­line all the new fea­tures.

Over­view of Swift 4

Swift 4 is a new ver­sion of the Swift pro­gram­ming lan­guage de­vel­oped by Ap­ple for iOS and

macOS de­vel­op­ment, adopting the best of C and Ob­jec­tive-C with­out the con­straints of C com­pat­i­bil­ity. It uses the same run­time as the ex­ist­ing Obj-C sys­tem on macOS and iOS, which en­ables Swift pro­grams to run on many ex­ist­ing iOS 6 and OS X 10.8 plat­forms.

• Swift 4 makes use of safe pro­gram­ming patterns

• Swift 4 pro­vides mod­ern pro­gram­ming fea­tures

• Swift 4 pro­vides seam­less ac­cess to ex­ist­ing Co­coa frame­works

• Swift 4 uni­fies the pro­ce­dural and ob­ject-ori­ented por­tions of the lan­guage

New fea­tures in Swift 4

Let’s look at the new el­e­ments in more de­tail.

String now con­forms to Col­lec­tion pro­to­col, and you can it­er­ate over String di­rectly. This also means you can use any Col­lec­tion meth­ods and prop­er­ties on String, like count, isEmpty, map(), fil­ter(), in­dex(of:), and so on.

Swift 4 takes a dif­fer­ent ap­proach for mul­ti­ple line strings by us­ing triple quotes in­stead, so you don’t have to es­cape dou­ble quotes any more:

Swift 4 sim­pli­fies the whole JSON archival and se­ri­al­i­sa­tion process you were used to in Swift 3. Now you only have to make your cus­tom types im­ple­ment the Cod­able pro­to­col – which com­bines both the En­cod­able and De­cod­able ones.

Swift 4 makes it eas­ier to ac­cess an ob­ject’s prop­er­ties with key paths.

You can com­bine pro­to­cols to­gether in Swift 3 when cre­at­ing con­stants and vari­ables. Swift 4 goes one step fur­ther and lets you add classes to the mix us­ing the same syn­tax. You may con­strain a cer­tain ob­ject to a class and a pro­to­col in just one go the same way as in Ob­jec­tive-C.

The swap(_:_:) mu­tat­ing method in Swift 3 takes two el­e­ments of a cer­tain ar­ray and swaps them on the spot. This so­lu­tion has one ma­jor draw­back: the swapped el­e­ments are passed to the func­tion as in­put pa­ram­e­ters so that it can ac­cess them di­rectly. Swift 4 takes a to­tally dif­fer­ent ap­proach by re­plac­ing the method with a swapAt(_:_:), which takes the two el­e­ments’ cor­re­spond­ing in­dices and swaps them just as be­fore.

You can use the dic­tionary’s init(uniqueKeysWithValues:) ini­tialiser to cre­ate a brand-new dic­tionary from a tu­ples ar­ray.

Why you should code in Swift 4

1. Swift is open source. Open source typ­i­cally means that the source code be­hind a pro­gram, or pro­gram­ming lan­guage, is made avail­able to the gen­eral pub­lic. Coders can then in­spect, mod­ify and de­ploy the pro­gram wher­ever they want.

Ap­ple’s Open Source page says: “Ap­ple be­lieves that us­ing Open Source method­ol­ogy makes macOS a more ro­bust, se­cure op­er­at­ing sys­tem, as its core com­po­nents have been sub­jected to the cru­cible of peer re­view for decades.”

2. Swift is easy to learn. Ap­ple built its lan­guage to be easy to use and with syn­tac­tic sim­plic­ity to match Python. The for­mat­ting does not re­quire semi-colons at the end of each line, and func­tions are eas­ier to un­der­stand.

3. Swift is fast. Ap­ple claims search al­go­rithms in Swift com­plete up to 2.6 times faster than Ob­jec­tive-C and up to 8.4 times faster than Python 2.7.

4. Swift is safe. When you work with the lan­guage, you shouldn’t come across any un­safe code and mod­ern pro­gram­ming con­ven­tions help keep re­quired se­cu­rity in your apps.

5. Swift is fa­mil­iar. If you’ve de­vel­oped soft­ware be­fore, you’ll find Swift’s syn­tax and con­cepts closely re­sem­ble those you al­ready use.

6. Play­grounds. Swift 4 comes with a fea­ture called Play­grounds, where Swift 4 pro­gram­mers can write their code and ex­e­cute it to see the re­sults im­me­di­ately.

7. Swift is the future of Ap­ple de­vel­op­ment.

8. Swift is en­ter­prise-ready. You can use Swift’s code on Linux (Ap­ple pro­vides pre-built Ubuntu bi­na­ries) and An­droid. That’s great for de­vel­op­ers cre­at­ing client/server so­lu­tions.

9. Swift is con­stantly im­prov­ing. Swift has been in use for more than three years, and it con­tin­ues to evolve with ev­ery up­date. We’re likely to hear more de­vel­op­ments at WWDC 2018.

Since Swift 4 has come into play, the com­piled bi­nary files size has been changed, which has re­sulted in the de­crease of app sizes; a mo­bile ap­pli­ca­tion used to weigh 20 MB, for ex­am­ple, and in the new­est Swift ver­sion it will take around 17MB. And there has been bug fix­ing, and the lan­guage has be­come faster.

10. Swift’s mem­ory is man­aged. De­vel­op­ers do not have to man­age mem­ory al­lo­ca­tions: vari­ables are ini­tialised be­fore use, ar­rays and in­te­gers are checked for over­flow and mem­ory is man­aged

au­to­mat­i­cally. This makes the Swift pro­gram­ming lan­guage safer to use for de­vel­op­ers who aren’t quite as ex­pe­ri­enced.

How to get started with Swift 4

In or­der to de­velop apps for iOS, you will need a Mac and a piece of soft­ware called Xcode. Fol­low the steps be­low to get started:

• Open the Mac App Store on your Desk­top

• Search for ‘Xcode’ in the search bar

• Click ‘Get’ next to the Xcode icon On­line com­pil­ers: There are lots of on­line com­pil­ers avail­able that will help you learn and ex­e­cute Swift code, but most of them are still geared to­wards Swift 3. The only com­piler that sup­ports Swift 4 can be found at fave.co/2tk­fk2x.

How to write a sim­ple App in Swift

Open Xcode, and se­lect File > New > Project. Then choose a suit­able tem­plate: in our case we will be us­ing a Sin­gle View App.

Fill in the de­tails as re­quired (just put your own name for Or­ga­ni­za­tion Name if you don’t work for a com­pany). The Or­ga­ni­za­tion Iden­ti­fier is usu­ally your com­pany’s URL in re­v­erse or­der. Se­lect the Lan­guage as Swift and tap Next.

Se­lect the lo­ca­tion where you want to cre­ate your project and you’re done. Xcode will cre­ate a project for you at your de­sired lo­ca­tion. Upon cre­ation of the project you will be pre­sented with the screen at the top of the next page.

We will be de­vel­op­ing an app to show the text “Hello world” on the screen along with the cur­rent date, with the back­ground colour set to grey.

Go to the ‘Main.sto­ry­board’ file in the left pane. Drag and drop a la­bel from the bot­tom-right cor­ner on to the view and set its text to ‘Hello World’ in the top-right cor­ner.

Now se­lect View in the left pane and set the back­ground colour to light grey. Run the app by click­ing the play but­ton in the top-left cor­ner. (And make sure an ap­pro­pri­ate choice of iPhone sim­u­la­tor is se­lected to the right of the play but­ton: in our case it’s iPhone 8 Plus. See op­po­site screen.)

Now dou­ble-click ‘view­con­troller.m’. It will open in a sep­a­rate win­dow. Now se­lect the La­bel in the sto­ry­board by right-click­ing and drag to ‘view­con­troller.m’ to cre­ate an out­let for the la­bel. Out­lets are used to ac­cess the con­trols in sto­ry­board in our code. When the user drag and drops an out­let, it will ask for the out­let name. En­ter ‘la­bel’.

Now copy and paste the fol­low­ing code in the viewDidLoad() method of ‘view­con­troller.m’.

let date = Date()

let for­mat­ter = DateFor­mat­ter() for­mat­ter.dateFor­mat = “dd.MM.yyyy” // set­ting the date for­mat let re­sult = for­mat­ter.string(from: date) self.la­bel.text = “Hello World “+ re­sult

Your code should look like the screen­shot at the top of the fol­low­ing page.

When you tap the run (play) but­ton the app builds, the sim­u­la­tor is launched and our app is in­stalled on the sim­u­la­tor, af­ter which the app opens and it shows us the screen be­low with “Hello World!” and the cur­rent date. We have suc­cess­fully cre­ated our first iOS app us­ing Swift.

(If the text in­side the la­bel crops, in­crease the width of the la­bel by drag­ging the edges.)

More ad­vanced Swift 4 meth­ods

We’ve made a sim­ple app. Now let’s move on to some meth­ods and code snippets you can use in your own app projects.

Use ‘let’ to make a con­stant and ‘var’ to de­fine a vari­able. The value of a con­stant can­not be changed

once as­signed; the value of a vari­able will change. User don’t al­ways have to write the type ex­plic­itly. Pro­vid­ing a value when you cre­ate a con­stant or vari­able lets the com­piler in­fer its type.

let con­stVar = 42 var num­berVar = 27

User can also spec­ify the type:

var num­berVar: Int = 27

Com­ments in Swift can be of two types.

Sin­gle line:

//This is a com­ment

Mul­ti­ple-line com­ments:

/* This is a Mul­ti­line com­ment */

The syn­tax of an if state­ment in Swift 4 is as fol­lows:

if boolean_­ex­pres­sion { /* state­ment(s) will ex­e­cute if the bool­ean ex­pres­sion is true */ }

For ex­am­ple: The syn­tax of an if...else state­ment in Swift 4 is as fol­lows:

if boolean_­ex­pres­sion { /* state­ment(s) will ex­e­cute if the bool­ean ex­pres­sion is true */ } else { /* state­ment(s) will ex­e­cute if the bool­ean ex­pres­sion is false */ }

For ex­am­ple: The syn­tax of an if...else if...else state­ment in Swift 4 is as fol­lows:

if boolean_­ex­pres­sion_1 { /* Ex­e­cutes when the bool­ean ex­pres­sion 1 is true */ } else if boolean_­ex­pres­sion_2 { /* Ex­e­cutes when the bool­ean ex­pres­sion 2 is true */ } else if boolean_­ex­pres­sion_3 { /* Ex­e­cutes when the bool­ean ex­pres­sion 3 is true */ } else { /* Ex­e­cutes when the none of the above con­di­tion is true */ }

For ex­am­ple:

Fol­low­ing is generic syn­tax of a switch state­ment in Swift 4. Here if fall through is used then it will con­tinue with the ex­e­cu­tion of the next case and then come out of the Switch state­ment.

Switch ex­pres­sion { case ex­pres­sion1 : state­ment(s)

fallthrough /* op­tional */ case ex­pres­sion2, ex­pres­sion3 : state­ment(s)

fallthrough /* op­tional */ de­fault : /* Op­tional */ state­ment(s);

For ex­am­ple:

Cre­ate ar­rays and dic­tio­nar­ies us­ing square brack­ets, and ac­cess their el­e­ments by writ­ing the in­dex or key in­side the brack­ets. The fol­low­ing line cre­ates an ar­ray.

var ar­rayList = [“Ap­ple”, “Mango”, “Ba­nana”, “Grapes”]

To ac­cess and mod­ify the sec­ond el­e­ment of an ar­ray we can di­rectly write:

ar­rayList[1] = “Water­melon”

To cre­ate an empty ar­ray, use the ini­tialiser syn­tax.

var emp­tyAr­ray = [String]()

emp­tyAr­ray = []

Dic­tio­nar­ies var oc­cu­pa­tions = [“Steve”: “Captain”, “Kate”: “Me­chanic”,]

To ac­cess and mod­ify any value for a dic­tionary we can di­rectly write:

oc­cu­pa­tions[“Steve”] = “En­gi­neer”

To cre­ate an empty dic­tionary, use the ini­tialiser syn­tax.

oc­cu­pa­tions = [:]

Sets in Swift are sim­i­lar to ar­ray but they only con­tain unique val­ues.

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

Swift also in­tro­duces the Op­tion­als type, which han­dles the ab­sence of a value. Op­tion­als say

ei­ther “there is a value, and it equals x” or “there isn’t a value at all”. You can de­fine an Op­tional with ‘?’ or ‘!’

var myString: String?

‘?’ means the value can be present or ab­sent.

‘!’ means the value can be nil ini­tially, but in future it has to have a value, or it will throw a com­piler error.

No sign means the vari­able is not op­tional and it has to be as­signed a value, or it will throw a com­piler error.

Fol­low­ing is the syn­tax to cre­ate a func­tion in Swift: the in­putNum is the pa­ram­e­ter name fol­lowed by the DataType, ‘cre­ateStr’ is the name of the func­tion. ‘-> String’ de­notes the re­turn type. The func­tion takes In­te­ger as in­put and con­verts it into String and re­turns it.

func cre­ateStr(Num­ber in­putNum : Int) -> String

{ re­turn “\(in­putNum)” }

The func­tion can be called us­ing the be­low syn­tax:

cre­ateStr(Num­ber: 345)

Fol­low­ing is the syn­tax to cre­ate a Class Car. It has an op­tional mem­ber vari­able numOfPer­sons and a func­tion dis­playDe­tails()

class Car

{ var numOfPer­sons : Int? func dis­playDe­tails() { }

The class in­stance can be cre­ated us­ing the line be­low:

var myCar : Car = Car()

The ‘numOfPer­sons’ vari­able can be ini­tialised as be­low:

myCar.numOfPer­sons = 5

Clo­sures are anony­mous func­tions or­ga­nized as blocks and called any­where like C and Ob­jec­tive-C lan­guages. Clo­sures can be as­signed to vari­ables. Fol­low­ing is the syn­tax of a clo­sure in Swift.

(pa­ram­e­ters) −> re­turn type in state­ments }

Be­low is a sim­ple ex­am­ple. Here we are as­sign­ing a clo­sure to the vari­able sc­name. Then on the next line we are call­ing the clo­sure by call­ing the vari­able name.

Here’s another ex­am­ple of clo­sure which takes two vari­ables as in­put and di­vides them.

In Swift we can ex­tend the func­tion­al­ity of an ex­ist­ing class, struc­ture or enu­mer­a­tion type with the help of ex­ten­sions. Type func­tion­al­ity can be added with ex­ten­sions but over­rid­ing the func­tion­al­ity is not pos­si­ble this way.

In the be­low ex­am­ple we have a class car and we are adding an ex­ten­sion to the car to add another prop­erty to it. While ac­cess­ing the speed prop­erty, it can be ac­cessed di­rectly as if it be­longs to the class.

The tu­ple type is used to group mul­ti­ple val­ues in a sin­gle com­pound value. Here’s the syn­tax of Tu­ple dec­la­ra­tion:

var Tu­pleName = (Value1, value2,… any num­ber of val­ues)

Here’s a Tu­ple dec­la­ra­tion:

var er­ror501 = (501, “Not im­ple­mented”)

Best places to learn more about Swift 4

There are a num­ber of re­sources out there to help you start build­ing apps us­ing Swift 4. Some of the best op­tions are listed be­low:

Ap­ple Doc­u­men­ta­tion: The best place to learn Swift 4 is Ap­ple’s of­fi­cial doc­u­men­ta­tion for Swift at fave.co/2oHZlpY.

eBook: Ap­ple has re­leased an up-to-date eBook which is ex­tremely use­ful when learn­ing Swift 4: The Swift Pro­gram­ming Lan­guage (Swift 4.0.3). It’s avail­able at fave.co/2oIMZho.

Udemy: The big­gest on­line learn­ing re­source has sev­eral courses on iOS de­vel­op­ment with Swift 4. I have listed a cou­ple of the best ones be­low:

• iOS 11 & Swift 4: The Com­plete iOS App De­vel­op­ment Boot­camp. Avail­able at fave.co/2H67viG.

• iOS 11 & Swift 4: From Begin­ner to Paid Pro­fes­sional. Avail­able at fave.co/2H3N3PA.

Swift Pro­gram­ming in Easy Steps: This book, by the au­thor of this ar­ti­cle, will teach you how to build iOS apps from scratch and it’s fully il­lus­trated too. You can

get a copy at fave.co/2tka8vz.

We’ve got more re­sources in the next ar­ti­cle.

Newspapers in English

Newspapers from UK

© PressReader. All rights reserved.