Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Swift 3 New Features

You're reading from  Swift 3 New Features

Product type Book
Published in Oct 2016
Publisher Packt
ISBN-13 9781786469632
Pages 142 pages
Edition 1st Edition
Languages
Author (1):
Keith Elliott Keith Elliott
Profile icon Keith Elliott

Table of Contents (16) Chapters

Swift 3 New Features
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
1. What Were They Thinking? 2. Discovering New Territories – Linux at Last! 3. Migrating to Swift 3 to Be More Swifty 4. Changes to Swifts Core Will Have You Asking for More 5. Function and Operator Changes – New Ways to Get Things Done 6. Extra, Extra Collection and Closure Changes That Rock! 7. Hold onto Your Chair; Advanced Type Changes Are Here! 8. Oh Goodness! Look Whats New in the Foundation Framework 9. Improving Your Code with Xcode Server and LLDB Debugging 10. Exploring Swift on the Server

Chapter 8. Oh Goodness! Look Whats New in the Foundation Framework

Last year, Apple delivered a great talk on the benefits of using value types and protocol-oriented design patterns in our code. This year with Swift 3, the team at Apple added value types to the Foundation framework. Many of our favorite and heavily used classes now have value type equivalents. We will cover how to use Foundation value types throughout this chapter and have you wondering why value types weren't included with Swift from the beginning!

New to Foundation and made possible by Swift 3, the new measurements and units API https://developer.apple.com/reference/foundation/nsmeasurement addresses pain points that have been with Objective-C and Swift developers for a long time. Apple has created an extremely well thought out solution to our problems. We will use several examples to hammer in the concepts so that you will leave this chapter better prepared to handle your measurement challenges in the future.

Mutability and Foundation value types


One of the key concepts of the Swift language is to give developers the ability to control the mutability of their objects. We use let to make a value a constant and var to make the value a variable. However, certain types, when imported from Objective-C, do not provide easy mutability features. Swift 3 aims to change this by adding a new set of Foundation value types to wrap reference types in order to provide mutable options for developers. In fact, this really isn't all that new as Foundation already uses many value types in both Objective-C and Swift. Foundation has existing types such as primitives, Enumerations, Option sets, and C structure types that already were value types in previous versions of Swift and Objective-C.

To make the conversion from reference type to value type possible, Swift uses the copy-on-write technique for new value types whose underlying data contains more than just simple data. With copy-on-write, the value type represents...

Value types versus reference types


As a refresher, let's quickly cover the difference between value and reference types. Value types hold values and copy content on assignment or when they are passed to methods as a parameter.

let avg1: Double = 98.1 
var avg2 = avg1 
avg2 += 1.2   // -> 99.3 

In the preceding example, avg2 copies the value of avg1, and is free to change its value without affecting the value of avg1. Reference types, on the other hand, share content by default. Changing one of the variables will change the underlying value that each reference shares.

 
let dateComponents1 = NSDateComponents() 
dateComponents1.setValue(10, forComponent: .Day) 
dateComponents1.day // => 10 
var dateComponents2 = dateComponents1 
dateComponents2.setValue(2, forComponent: .Day) 
dateComponents1.day // => 2 
dateComponents2.day // => 2 

In this example, we use the reference type NSDateComponents to create dateComponents1 and set...

Nested enumerations


The Foundation framework takes advantage of Swift 3's new nested enumeration feature. This feature allows the migrator to import related Objective-C enumerations into Swift under a common type. For example, the NSDateFormatterStyle and NSDateFormatterBehavior enumerations are imported as nested enumerations to the DateFormatter class in Swift. Let's see how we get to a nested enumeration in Swift 3, starting with an Objective-C enumeration.

In Objective-C:

typedef NS_ENUM(NSUInteger, NSDateFormatterStyle), 
{ 
   NSDateFormatterNoStyle     = kCFDateFormatterNoStyle, 
   NSDateFormatterShortStyle  = kCFDateFormatterShortStyle, 
   NSDateFormatterMediumStyle = kCFDateFormatterMediumStyle, 
   NSDateFormatterLongStyle   = kCFDateFormatterLongStyle, 
   NSDateFormatterFullStyle   = kCFDateFormatterFullStyle 
}; 
 
typedef NS_ENUM(NSUInteger, NSDateFormatterBehavior){ 
   NSDateFormatterBehaviorDefault = 0, 
   NSDateFormatterBehavior10_0...

Strongly typed string enumerations


The Foundation framework has a lot of string-based constants. For example, UIKit uses NSNotifications to publishing notifications for an iOS app's lifecycle.

NSString *const UIApplicationDidEnterBackgroundNotification        
NSString *const UIApplicationWillEnterForegroundNotification      NSString *const UIApplicationDidFinishLaunchingNotification; 

New for Foundation, Objective-C now has the ability to use strongly typed string enumerations. This new feature allowed the Foundation team to update the enumerations in Objective-C. Our notifications listed earlier can now use the NSNotificationName type and convert our preceding constants to:

In Objective-C:

typedef NSString *NSNotificationName NS_EXTENSIBLE_STRING_ENUM; 
NSNotificationName const UIApplicationDidEnterBackgroundNotification        
NSNotificationName const UIApplicationWillEnterForegroundNotification      NSNotificationName const UIApplicationDidFinishLaunchingNotification...

Class properties


For historical reasons, the Foundation framework contains many cases where the state of a property is closely associated with the type. Therefore, you will find lots of class properties on Objective-C types. New for the Swift 3 release, we get a tweak to Objective-C that allows us to use a new syntax for creating class properties. These class properties in Objective-C will be imported into Swift as class properties as well.

In Objective-C (old way):

@interface NSCharacterSet  
+ (NSCharacterSet *)controlCharacterSet; 
+ (NSCharacterSet *)whitespaceCharacterSet; 
+ (NSCharacterSet *)whitespaceAndNewlineCharacterSet; 
@end 

In Objective-C (new way):

@interface NSCharacterSet  
@property(class, readonly, strong) controlCharacterSet; 
@property(class, readonly, strong) whitespaceCharacterSet; 
@property(class, readonly, strong) whitespaceAndNewlineCharacterSet; 
@end 

In Swift 2.2:

class NSCharacterSet{ 
 class func controlCharacters...

Type safe access with value types


New with Swift 3, you can use Foundation value types to get compile time checks to eliminate many of the errors that couldn't be discovered until runtime when using reference-based Foundation types. Let's work through an example that demonstrates a runtime check in Swift 2.2.

In Swift 2.2:

 
if let filePath = NSBundle.mainBundle().pathForResource("testFile", ofType: "txt"){ 
    let fileURL = NSURL.fileURLWithPath(filePath) 
    let keys = [NSURLCreationDateKey, NSURLPathKey, NSURLFileSizeKey,NSURLTagNamesKey] 
    var values = try fileURL.resourceValuesForKeys(keys) 
    if let creationDate = values[NSURLCreationDateKey]{ 
        print("creationDate: \(creationDate)") 
    } 
     
    values[NSURLTagNamesKey] = ["test", "sample", "playground"] 
    values[NSURLCreationDateKey] = "now"   // à creates an error 
    print(values[NSURLTagNamesKey]) 
    print(values[NSURLCreationDateKey]) 
  ...

Measurements and units


With Swift 3's release, the Foundation team is releasing a new API to make handling measurements easier for developers. By allowing developers to create measurements from common built-in units (or create custom ones), convert between units and format them for display. We will cover each of the main areas of the Measurement API to get you ready to use them in your projects.

Measurement

A measurement is composed of a unit and a value. A unit is a class that contains a single property to hold a symbol. We will come back to units in a moment. For now, let's focus on what you can do with a measurement.

public struct Measurement<UnitType : Unit> : ReferenceConvertible, Comparable, Equatable { 
 
    public typealias ReferenceType = NSMeasurement 
 
    /// The unit component of the `Measurement`. 
    public let unit: UnitType 
 
    /// The value component of the `Measurement`. 
    public var value: Double 
 
    //...

Summary


In this chapter, we covered changes to the Foundation framework. We started with a discussion on mutability and new value types in Foundation. You learned that both value and reference types have their place in our code. Next, we covered nested enumerations and strongly typed string enumerations. We explored class properties and the type-safe access benefits of value types. Finally, we spent a great deal of time discussing the new Measurements API introduced this year in Foundation. In the next chapter, we will cover testing and debugging. Swift 3 introduces several changes in testing and debugging that should help improve the quality of the code you write.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Swift 3 New Features
Published in: Oct 2016 Publisher: Packt ISBN-13: 9781786469632
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}