Become Swift 3 Jedi Master

6 tips to become a better Swift 3 developer

Swift is the definitive language of Apple development
It’s a vital part of any iOS and OS X developer’s skillset, helping them to build the most impressive and popular apps on the App Store.

Swift adds language features that make developers’ code safer, faster, more reliable, and more predictable compared to Objective-C.

1 Create a Swift file to mange your style

The cleanest & simplest way to set your appearance properties:

Set colours and fonts for every label or button you create, simply create a Swift file that extends certain classes. You can change the style of your App in two minutes. 🎨

Use static, computed variables. Swift 3 allows us to use variables without any initialisers.
// Colors.swift 
extension UIColor {
static var buttonColor:UIColor {
return UIColor(red: 0.50, green: 0.50, blue: 0.50, alpha: 1)
}
static var bodyColor:UIColor {
return UIColor(red: 0.30, green: 0.0, blue: 0.30, alpha: 1)
}
static var backgroundColor:UIColor {
return UIColor(red: 0.00, green: 0.7, blue: 0.40, alpha: 1)
}
}
// FontStyles.swift
extension UIFont {
static var bodyFont:UIFont {
return UIFont(name: "Helvetica", size: 14)
}
static var titleFont:UIFont {
return UIFont(name: "Helvetica-Bold", size: 18)
}
}

Setup a label with and without the extensions:

let label = UILabel()
// without extensions
label.textColor = UIColor(red: 0.30, green: 0.0, blue: 0.30, alpha: 1)
label.font = UIFont(name: "Helvetica", size: 14)


// with extensions
label.textColor = .bodyColor
label.font = .bodyFont

2 Use Realm Mobile Database

Realm Mobile Database is an alternative to SQLite and Core Data. Thanks to its zero-copy design, Realm Mobile Database is much faster than an ORM, and often faster than raw SQLite. Get started in minutes, not hours.

2.1 Benefits of a database built for mobile:

  • Offline-first functionality
  • Fast queries
  • Safe threading
  • Cross-platform apps
  • Encryption
  • Reactive architecture

2.2 Simplify your code

Just subclass Object to define your schema, persist with lightweight transactions, and query using NSPredicate. Working with your data should always be this easy.

class Dog: Object {
dynamic var name = ""
dynamic var age = 0
}

let dog = Dog()
dog.name = "Rex"
dog.age = 1

let realm = try! Realm()
try! realm.write {
realm.add(dog)
}

let pups = realm.objects(Dog.self).filter("age < 2")

2.3 Get Started

  1. Install CocoaPods 0.39.0 or later.
  2. Run pod repo update to make CocoaPods aware of the latest available Realm versions.
  3. In your Podfile, add use_frameworks! and pod ‘RealmSwift’ to your main and test targets.
  4. Paste the following at the bottom of your Podfile, updating the Swift version if necessary:
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['SWIFT_VERSION'] = '3.0'
end
end
end

More details https://realm.io/docs/swift/latest

3 C-style unary operator

The C-style unary operators ++ and -- are not available anymore in 3.0 version:

// Swift 2.3 and earlier
var number = 10
number++
++number
number--
--number
// Swift 3.0
var number = 10
number += 1
number -= 1

4 Learn and Experiment in the Playground Environment

A playground is an interactive coding environment for Swift. We can create playgrounds to test and validate ideas, learn Swift, and share concepts with each other.

4.1 Create a playground

To create a playground simply open Xcode launch and click on “Get started with a playground

Playgrounds are a great way to prototype and demonstrate ideas in code without the overhead of starting a project.

4.1 Swift Playgrounds on your iPad (for beginners)

Watch the Apple video demo

Swift Playgrounds is a revolutionary new app for iPad that makes learning Swift interactive and fun. Then take on a series of challenges and step up to more advanced creations. Swift Playgrounds requires no coding knowledge, so it’s perfect for students just starting out. It also provides a unique way for seasoned developers to quickly bring ideas to life. And because it’s built to take full advantage of iPad, it’s a first-of-its-kind learning experience.

Download Swift Playgrounds free

5 Define Global Constants

The best way to define a global constant is to create a Struct:

// Constants.swift
struct Constants {
   struct Path {
static let myAPI = "https://api.mywebsite.com/"
static let twitterAPI = "https://api.twitter.com/"
struct Services {
static let service1 = "https://service1.mywebsite.com/"
static let service2 = "https://service2.mywebsite.com/"
}
}
   struct Default {
static let currency = "euro"
}
}

Ok now we can try to print two constants:

print(Constants.Path.Services.service1)
print(Constants.Default.currency)

This is useful because Swift allows us to nest structures.

6 Define Global Functions

Global functions and variables can help you make clean code.

We’re going to start with an preatty simple extension, this function provide to animate an object UIView o other subview like UIButton or UILabel.

The extension Int tells Swift that we want to add functionality to its UIView struct. We could have used String, Array, UIButton or whatever instead.

extension UIView {
   func pushTransition(duration:CFTimeInterval) {
      let animation:CATransition = CATransition()
      animation.timingFunction = CAMediaTimingFunction(name:
         kCAMediaTimingFunctionEaseInEaseOut)
      animation.type = kCATransitionPush
      animation.subtype = kCATransitionFromTop
      animation.duration = duration
      self.layer.addAnimation(animation, forKey: kCATransitionPush)

}
}

Let’s try to animate a Label

let myLabel = UILabel()
// customize myLabel
myLabel.pushTransition(1.0)

Download source code

Check out the example source code on Github.


A good book to learn more

Mastering Swift 3


If you enjoyed this article please recommend and share.
This is the post you are looking for.
Like what you read? Give Enrico Piovesan a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.