Codementor Events

Swift 4.0 key features

Published Jan 27, 2019
Swift 4.0 key features

Swift 4

The Swift 4 is a major release, It will contain significant enhancements to the core language and Standard Library, especially in the generics system and a revamp of the Stringtype.

The Swift 4 key focus is to become more user friendly system and update its API and performance. These changes are source-breaking, and thus will require existing code to migrate to using the new APIs.

Stage 1 : focused on the essentials required for source and ABI stability. Features that don't fundamentally change the ABI of existing language features or imply an ABI-breaking change to the standard library will not be considered in this stage.

Stage 2 : opened in mid-February and extends until April 1, 2017, after which proposals will be held for a later version of Swift.

The Swift 4 release is designed around two primary goals: to provide source stability for Swift 3 code and to provide ABI stability for the Swift standard library. To that end, the Swift 4 release will be divided into two stages.

Below are some major changes in Swift 4 release :

Limiting @objc inference

  • Info

One can explicitly write @objc on any Swift declaration that can be expressed in Objective-C. As a convenience, Swift also infers @objc in a number of places to improve interoperability with Objective-C and eliminate boilerplate.

This proposal scales back the inference of @objc to only those cases where the declaration must be available to Objective-C to maintain semantic coherence of the model,
e.g., when overriding an @objc method or implementing a requirement of an @objc protocol. Other cases currently supported (e.g., a method declared in a subclass of NSObject) would no longer infer @objc, but one could continue to write it explicitly to produce Objective-C entry points.

  • Some Examples...
  1. Objective-C selector collisions due to overloading :

Old One :

class MyNumber : NSObject {
 init(_ int: Int) { }
 init(_ double: Double) { } // error: initializer 'init' with Objective-C selector 'init:' 
     // conflicts with previous declaration with the same Objective-C selector
}

New One :

 class MyNumber : NSObject {
  @objc(initWithInteger:) init(_ int: Int) { }
  @objc(initWithDouble:) init(_ double: Double) { }
}
  1. The declaration is an override of an @objc declaration :
class Super {
    @objc func foo() { }
}
class Sub : Super {
    /* inferred @objc */
    override func foo() { }
}

Note : This inference is required so that > Objective-C callers to the method Super.foo() will appropriately invoke the overriding method Sub.foo().

  1. The declaration satisfies a requirement of an @objc protocol :
@objc protocol MyDelegate {
    func bar()
}
class MyClass : MyDelegate {
    /* inferred @objc */
    func bar() { }
}

Note : This inference is required because anyone calling MyDelegate.bar(), whether from Objective-C or Swift, will do so via an Objective-C message send, so conforming to the protocol requires an Objective-C entry point.

Improve Interaction Between private Declarations and Extensions

  • Info

Swift 4, we can now provide the private access level to make it accessible to a extension of the same type.

  • Example
struct India {
    private var lang = ["Hindi"]
}
extension India {
    mutating func add(language: String) {
    lang.append(language)
}

// error: 'lang' is inaccessible due to 'private' protection level
Note : Swift 4 now you can access lang via an extension using private.

Distinguish between single-tuple and multiple-argument function types

  • Info
    you can now have to manually expand tuples from the now-single parameter.

  • Example
    Create One Tuple :

typealias Person = (firstName: String, lastName: String)
let persons: [Person] = [("Dany", "Bosto")]

Old Usage :

persons.forEach({ first, last in
    print(last)  // "Bosto"
})

In Swift 4 :

persons.forEach({ name in
    print(person.lastName)         // "Bosto"
})
persons.forEach({ name in
    let (first, last) = person
    print(last)                  // "Bosto"})

Codable Protocol for data type serialize and deserialize

  • Info

Swift 4 added a new Codable protocol that lets you serialize and deserialize custom data types without writing any extra code – and without having to worry about losing your value types.
Even better, you can choose how you want the data to be serialized: you can use classic property list format or even JSON.

  • Example

Create one custom data type :

struct Language: Codable {
    var name: String
    var version: Int
}

let swift = Language(name: "Swift", version: 4.0)
let objC = Language(name: "Objective-C", version: 2.2)
let cSharp = Language(name: "C#", version: 5.0)

In Swift 4 usage :

if let encoded = try? encoder.encode(swift) {
    // Encoding
    if let json = String(data: encoded, encoding: .utf8) {
        print(json)
    }

    // Decoding
    let decoder = JSONDecoder()
    if let decoded = try? decoder.decode(Language.self, from: encoded) {
        print(decoded.name)
    }
}

Note : In above decoding we didn't required any typecasting.

Some Foundation Types Adopting Codables...

AffineTransform
Calendar
CharacterSet
Date
DateComponents
DateInterval
Decimal
IndexPath
IndexSet
Locale
Measurement
Notification
PersonNameComponents
TimeZone
URL
URLComponents
URLRequest
UUID

The following Foundation Swift types will be adopting Codable, and will encode as their bridged types when encoded through NSKeyedArchiver, as mentioned above:
Along with these, the Array, Dictionary, and Set types will gain Codable conformance (as part of the Conditional Conformance feature), and encode through NSKeyedArchiver as NSArray, NSDictionary, and NSSet respectively.

Able to add multi line string in code

  • Info

Now in swift 4 we can add multi line string without using \n and you can add line break when you need. You can use double quote into this long string. Just you have to add """ 3 quote at start & end of the string.

  • Example
let veryLongString = """
Lorem ipsum dolor sit amet,
 eam an errem quando invidunt,
 nam equidem vivendum ne. "Movet graecis expetenda ea qui",
 magna imperdiet usu ea. Quodsi dissentiet ei eos,
 eligendi accommodare vis ea. Equidem principes concludaturque ei eos.
 Te vis aeque hendrerit, ius cu quem periculis deseruisse.
 Eam utinam mollis regione eu, eu vis propriae efficiendi,
 ad nec assum scribentur.
"""

Use String agin as collections

  • Info
    Very Small but interesting and useful change in string, Now we can use string as character array and can reverse it.

  • Example

let myString = "Swift language is awesome and i love to write code in Swift"
let reversedMyString = myString.reversed()

for char in reversedMyString {
    print(char)
}

Multiple Range in collection slicing

  • Info

Now we can use collection with multiple slicing and can split array into different slicing like below.

  • Example
let actors = ["Johnny Depp", "Al Pacino", "Robert De Niro", "Angelina Jolie", "Tom Cruise"]
let firstSlice = characters[..<3]
let lastSlice = characters[3...]
//Now Lets Print Both Slice
print(firstSlice)
print(firstSlice)

//Out Put
firstSlice : ["Johnny Depp", "Al Pacino","Robert De Niro"]
lastSlice : ["Angelina Jolie", "Tom Cruise"]

For More Information you can use below link for Reference :

Github Swift Evolution

Swift.org blog

How to migrate in Swift 4.0

Hope above information will helps to drive your project or code in Swift 4.0.

Happy Coding !

Discover and read more posts from dgosai
get started
post commentsBe the first to share your opinion
Show more replies