Xcode 8 Release Notes

Technical Support and Learning Resources

Apple provides the following web resources to support your development with Xcode:

To provide feedback to the Xcode team, file a bug report at bugreport.apple.com.

Compatibility

Release Notes Updates

Xcode Release Notes is sometimes updated after a release is distributed. You can check for the most up-to-date version of Xcode Release Notes at the Apple Developer website by checking https://developer.apple.com/library/etc/redirect/xcode/release_notes.

Revision: XC821 - XRN3

Release Notes Archive

For release notes pertaining to previous releases of Xcode, see Xcode Release Notes — Archive.

Xcode 8.2.1 Update

Swift

Resolved Issues

  • Fixed an issue that could cause building a project to fail with the error message “"Use Legacy Swift Language Version" (SWIFT_VERSION) is required to be configured correctly for targets which use Swift” when using a supported version of Swift. (29667880)

  • Xcode no longer warns about using deprecated Swift 2.3 code when the active scheme does not reference targets using Swift 2.3 code. (29671741)

Known Issues

  • "Convert to Current Swift Syntax" only converts targets referenced by the active scheme. (13997108)

Xcode 8.2 Update

General

New Features

  • Xcode 8.2 offers more Touch Bar actions and allows customizing the Touch Bar controls of the following editors and debuggers: source editor, Playground editor, Interface Builder, view debugger, and memory graph debugger. To customize the Touch Bar, open the desired editor and then choose View > Customize Touch Bar. (28462580)

  • Touch Bar API is available for macOS 10.12.2 or later. (28785230, 28785231)

Asset Catalog

Known Issues

  • Builds of iOS, tvOS, and watchOS targets may hang during CompileAssetCatalog, CompileStoryboard, or CompileXIB when running on OS X El Capitan. (28422833)

    Workaround: Rebuild the target.

Building and Linking

Resolved Issues

  • Using .xcconfig files will not cause projects to prompt about changes on disk when switching git branches. (28794807)

Command Line Tools

Resolved Issues

  • Command Line Tools (OS X 10.11) for Xcode 8.2 are available and support Swift 3.0 development from the command line on OS X El Capitan. (28234439)

Core Data

Resolved Issues

  • Opening a data model with a minimum tools version earlier than Xcode 8.0 will not reset the code generation language to Objective-C. (29032095)

Debugging

Resolved Issues

  • The Memory Debugger for macOS and the iOS Simulator fixes reporting of false memory leaks for Swift classes containing either fields of type enum, or classes that inherit from certain Objective-C framework classes. (27932061)

    False reporting can still occur for iOS, watchOS, and tvOS applications. See (29335813) in Known Issues, below.

Known Issues

  • The Memory Debugger for iOS, watchOS, and tvOS applications can report false memory leaks when debugging Swift classes containing either fields of type enum, or classes that inherit from certain Objective-C framework classes. (29335813)

Interface Builder

Resolved Issues

  • A UITabBarController correctly displays content instead of blue boxes. (27881406)

  • Fixed a crash on macOS 10.12 when a P3 color space other than the system default is installed. (26178719)

  • The supportsPressAndHold property works when using popover Touch Bar items from Interface Builder. (28701667)

Simulator

New Features

  • Dragging an app onto a Simulator window installs the app. (23387069)

  • You can take videos and screenshots of Simulator using the xcrun Xcode command-line utility. To take a screenshot, run the command xcrun simctl io booted screenshot. To take a video, run the command xcrun simctl io booted recordVideo <filename>.<file extension>. (9887264)

Resolved Issues

  • Dragging a Live Photo resource into the Simulator imports the Live Photo instead of importing a photo and a video. (27906875)

  • Simulator renders the screen correctly when using iOS 9.1 or earlier. (27996364)

  • Keychain APIs work correctly in Simulator. (28338972)

Known Issues

  • Simulator can crash when saving a screenshot when running on OS X El Capitan. (29182710)

    The crash does not occur on macOS Sierra.

Swift

Resolved Issues

  • Extensions which make imported Objective-C generic classes conform to protocols defined in Swift are compiled correctly. (28873860)

  • Objective-C generic types show as defined in generated headers with a suffix of -Swift.h. (28738008)

  • Type inference will properly unwrap optionals when used with generics and implicitly-unwrapped optionals. (28621624)

  • NSFileManager's enumerate(at:includingPropertiesForKeys:options:errorHandler:) method passes valid URLs to the error handler in code compiled with Swift 3.0.2.

    There may still be some Objective-C methods in the SDKs that incorrectly annotate or assume a type to be nonnull rather than nullable. If the type is one that Swift treats as a struct, such as NSURL (Foundation.URL) or NSDate (Foundation.Date), this can lead to a run-time crash in a method with a name like bridgeFromObjectiveC; in other cases, it can lead to crashes or undefined behavior in user code. If you identify such a method, please file a report at bugreport.apple.com. For reference, the (now unnecessary) workaround for the newly-fixed NSFileManager API is shown below; it can be adapted for whichever API you want to call.

    static inline NSDirectoryEnumerator<NSURL *> * _Nullable
    fileManagerEnumeratorAtURL(NSFileManager *fileManager, NSURL * _Nonnull url,
                               NSArray<NSURLResourceKey> * _Nullable keys,
                               NSDirectoryEnumerationOptions options,
                               BOOL (^ _Nullable errorHandler)
                               (NSURL * _Nullable errorURL, NSError * _Nonnull error)) {
                                    return [fileManager enumeratorAtURL:url
                                             includingPropertiesForKeys:keys
                                                                options:options
                               errorHandler:^(NSURL * _Nonnull errorURL, NSError * _Nonnull error) {
                                   return errorHandler(errorURL, error);
                               }];
    }

    This function can be included in your bridging header (for an app or test target) or umbrella header (for a framework target). (27749845)

Known Issues

  • The Swift compiler may crash if a nested computed get-only property is defined and accessed within a generic function, a method of a protocol extension, or a method of a generic type. (28933116)

    For example:

    protocol Runcible {}
     
    extension Runcible {
       func runce() -> Int {
          // Property definition crashes the compiler
          var localProperty: Int {
             print(self)
             return 0
          }
          return localProperty
       }
    }

    Workaround: Redefine the property as a nested function or provide a setter.

  • The Swift compiler may crash when an array of tuples is converted to add or remove element labels. (28425149)

    For example:

    typealias Foo = (x: Int, y: Int)
    let foos = [(0, 0), (1, 1)] // has inferred type [(Int, Int)]
     
    func getFoos() -> [Foo] {
       // Attempts implicit conversion from [(Int, Int)] to [(x: Int, y: Int)]
       return foos
    }

    Workaround: Avoid mixing array types of labeled tuples with arrays of unlabeled tuples.

  • The Swift compiler may crash if a method of a nested type refers to a nested function in the same scope. (28015090)

    For example:

    do {
       func foo() {}
     
       class Bar {
          init() {
             //the following line crashes the compiler
             foo()
          }
       }
    }

    Workaround: Move the function to the top level to avoid the crash.

    For example, the following code shows the workaround for the example given above:

    // Move the function to the top level
    func foo() {}
     
    do {
       class Bar {
          init() {
             foo()
          }
       }
    }
  • When an NSDictionary is bridged into Swift as a Dictionary with AnyHashable keys, then using Swift integer values to index the dictionary may fail to find objects inside the dictionary. (29026017)

    For example:

    NSDictionary *makeDict() {
       return @{@(NSOrderedAscending): @"ascending"};
    }
    let dict = makeDict()
    // Fails to find key in dictionary
    dict[NSComparisonResult.orderedAscending.rawValue]

    Workaround: Explicitly construct an NSNumber instance for the dictionary lookup key.

    For example, the following code shows the workaround for the example given above:

    dict[NSNumber(value: NSComparisonResult.orderedAscending.rawValue)]

Deprecations

  • Xcode 8.2 is the last release that will support Swift 2.3.  Please migrate your projects to Swift 2.3 code to Swift 3 syntax by opening the project and choosing Edit > Convert > To Current Swift Syntax.

Testing

Known Issues

  • The Touch Bar simulator window can interfere with mouse events during macOS UI tests.

    Workaround: As a temporary workaround, set the IDETestingDisableTouchBarSimulatorWindowBehavior user default to a YES to prevent the window from appearing during testing. (28531281, 28802822)

    1. Quit Xcode if it's running.

    2. Open the Terminal and enter the following command:

      defaults write com.apple.dt.xcode IDETestingDisableTouchBarSimulatorWindowBehavior -bool YES

Xcode 8.1 Update

General

New Features

  • Xcode 8.1 supports Touch Bar for Macs that include it, and supports adding Touch Bar functionality to your app. (28859277)

    Before using Touch Bar functionality in your app, confirm that the app is running on a macOS version that includes support for Touch Bar using a runtime check.

    • For example, the following Objective-C code performs a runtime check to make sure NSTouchBar is available:

      NSClassFromString(@"NSTouchBar") != nil
    • In Swift code, do an availability check for macOS 10.12.1, and a runtime check for Touch Bar class availability. For example:

      NSClassFromString("NSTouchBar") != nil

Known Issues

  • When an Xcode project is stored in iCloud Drive, Xcode does not automatically detect iCloud Drive sync conflicts for projects or for files involved in the build. Note that the Documents and Desktop folders can be stored in iCloud Drive on macOS 10.12. (18161353)

  • Opening Xcode projects and workspaces stored in iCloud Drive, or changing source control branches for an open workspace or project stored in iCloud Drive, may sometimes cause Xcode to hang. Note that in macOS 10.12, your Documents and Desktop folders may optionally be iCloud Drive locations. (28212905)

Building and Linking

Deprecations

  • OS X 10.11 was the last major release of macOS that supported the previously deprecated garbage collection runtime.  Applications or features that depend upon garbage collection may not function properly or will not launch in macOS Sierra. Developers should use Automatic Reference Counting (ARC) or manual retain/release for memory management instead. (20589595)

Command Line Tools

Resolved Issues

  • The simctllaunch subcommand in xcrun now supports directing the app’s standard out and standard error to a file or to the local terminal. (27636817)

Known Issues

  • There is no Command Line Tools (OS X 10.11) for Xcode 8.1 beta 2 package. Xcode 8.1 beta 2 contains SDKs that are incompatible with earlier toolchains. Developers who want to make use of the Xcode 8 beta 2 SDKs from the command line must choose the SDK with xcode-select. Developers on OS X El Capitan who have installed versions of the Command Line Tools (OS X 10.11) for Xcode 8.1 beta 2 should install Command Line Tools (OS X 10.11) for Xcode 7.3.1. (28234439)

Core Data

New Features

  • Adding a new entity to an Xcode 8 or later Core Data model sets the entity name and the class name to the same value. Changing the entity name changes the class name, unless the class name is different than the entity name. (27896843)

Resolved Issues

  • When using Core Data automatic code generation, changes made to a data model are now available after the model is saved or autosaved. (25789848)

Known Issues

  • In the Core Data editor, setting the module of a Swift NSManagedObject subclass to Current Product Module can cause Swift code generation to use an incorrect filename for the generated code, and to generate an empty import statement for other NSManagedObject subclasses. (26898508)

    As a workaround, set the contents of the Module field for the desired entity to the default value:

    1. In the Core Data editor, highlight the contents of the Module field for the desired entity.

    2. Press the Delete key.

      The Module field now shows the default value, "Global namespace," in light gray.

Debugging

Resolved Issues

  • Starting with macOS Sierra 10.12.1, Xcode 8.1 is required to debug processes that call exec() on themselves. For earlier Xcode versions, re-attach the debugger to the target process after the exec()] call. (28476369)

Known Issues

  • The Xcode debug button in the Touch Bar can sometimes remain in the Control Strip after a debug session has ended resulting in a button with no icon. The debug icon will re-appear in the button when starting a new debug session. (28776047)

  • Anonymous closure arguments in Swift cannot be used in LLDB expressions. For example, po $0 is not supported.

    The values can be inspected in the LLDB command frame variable in Xcode’s Variables View. For example, fr va $0 displays the current value of the first argument. (28611943)

  • A Top Shelf extension is not automatically triggered when you debug a tvOS app from Xcode. As a workaround, use the remote to select a different Top Shelf item and then go back to the one you want to debug. (26131040)

  • Evaluating expressions in the Xcode Debug Console attached to an Apple Watch can cause the process to be suspended. This occurs when debugging a Notification before the user interface is displayed, for example, during the -init method. As a workaround, manually launch the Watch app on the device to resume the process. To avoid suspending the process, you can use logging instead of a breakpoint. (27459900)

  • Xcode Debugger cannot debug apps written in Objective-C only but that link against frameworks written in Swift only. (28312362)

  • The first time you debug a Today extension on a device, it is not offered as an extension to run. As a workaround, stop the process, then run and debug it again. (26427188)

  • watchOS 1 apps may fail to finish launching on Apple Watch devices. (27724931)

Deprecations

  • Debugger() and DebugStr() are deprecated and the scheme editor no longer provides the option to enable these functions. If your project uses these functions, enable them by setting the environment variable USERBREAK with a value of 1. (24631170)

Help

Known Issues

  • Quick Help shows “Symbol not found” message for Objective-C user defined symbols. (28061632)

    Use HeaderDoc documentation tags to add Quick Help comments to your symbols. The following comment block shows the general format for documenting a method:

    /**
       @method myMethod:withTwoParameters:
       @abstract A short description for the QuickHelp popover
       @description A longer description for the QuickHelp pane
       @param paramName1 A description of the parameter
       @param paramName2 Another parameter description
       @return Description for the return value
    */

Instruments

Deprecations

  • The Automation instrument has been removed from Instruments. Use Xcode’s UI Testing instead. (26761665)

Interface Builder

New Features

  • Added Custom Gesture Recognizer to the object library. Use it for custom subclasses of UIGestureRecognizer or NSGestureRecognizer instead of a plain NSObject. This resolves an issue where a combination of stock and custom gesture recognizers on a UIView fails to compile. (27838954)

  • There is a new Update Frames button at the bottom of the canvas. Click the button to update the frames of the selected objects and their children on the Interface Builder canvas. (27818991)

  • The Pin button at the bottom of the canvas has been renamed to Add New Constraints. (27819014)

Resolved Issues

  • Dragging content into static UITableView cell on the canvas works again. (28026179)

  • Fixed auto layout performance issue with NSStackView using Gravity Areas distribution. (27910320)

  • Xcode 8.0 did not always restore view frames from storyboards and xibs when layouts were ambiguous. Xcode 8.1 fixes several of these issues. If you have encountered these issues, resolve the ambiguity in the Auto Layout issues and update frames. Xcode 8.1 will persist them correctly. (28221021, 28244619)

  • Resolved a layout hang when selecting Landscape orientation in the Device Bar on non-Retina displays when running on OS X 10.11. (27251685)

  • Xcode Debug Console no longer shows extra logging from system frameworks when debugging applications in the Simulator. (26652255, 27331147)

  • When using Swift 2.3, creating IBAction connections no longer inserts WithSender in the selector name. (25220368)

Known Issues

  • supportsPressAndHold does not work when using popover Touch Bar items from Interface Builder. (28701667)

    To work around this, add an outlet to the popover item in code and call popoverItem.pressAndHoldTouchBar = popoverItem.popoverTouchBar.

  • Using NSColorPickerTouchBarItem in Interface Builder results in a Touch Bar item that is disabled at runtime. (28670596)

    To enable the Touch Bar at runtime, add an outlet to the color picker item in code and call colorPickerItem.isEnabled = true.

  • Using NSSharingServicePickerTouchBarItem in Interface Builder results in a disabled Touch Bar item with a blank image. (28716331)

    To set the image and enable the service picker at runtime, add an outlet to the service picker and set the image by calling servicePicker.buttonImage = NSImage(named: NSImageNameTouchBarShareTemplate). Then enable the service picker by calling servicePicker.isEnabled = true.

  • Creating an IBAction connection by control-dragging when using Swift 2.3 incorrectly includes WithSender in the selector, causing the application to crash at runtime. WithSender is added when control-dragging from a .swift file to the Interface Builder canvas, or when control-dragging from the canvas to the document outline. As a workaround, create the action connection by dragging from Interface Builder to the Swift source, or use Find > Find and Replace to manually remove WithSender. (27410040)

  • Interface Builder does not show correct bar heights (status bar, top bar, bottom bar) when picking landscape for a device in the device configuration bar. (6799670)

Objective-C and C++

New Features

  • Objective-C now supports ARC-style weak references in files using manual reference counting (MRC). This behavior must be manually enabled in your project settings. __weak was previously accepted and ignored in MRC files; to avoid silently changing the behavior of code, if weak references are not enabled, the compiler will now warn on such uses of __weak. (28694859)

  • Manual reference counting (MRC) weak references are fully supported on macOS 10.12 Sierra, iOS 10.0, watchOS 3.0, and tvOS 10.0.

    MRC weak references are partially supported on macOS Lion 10.7 through macOS El Capitan 10.11, iOS 5.0 through 9.0, watchOS 1.0 and 2.0, and tvOS 9.0. These versions do not support runtime metadata for __weak instance variables in classes whose @implementation is defined in MRC. Also NSCopyObject() will not work, and direct access to ivars by Key-Value Coding and Interface Builder will not work. To work around this, use KVC and IBOutlet on accessor methods or properties. (9674298)

Project Editor

Known Issues

  • The “Use Asset Catalog…” button in the Project Editor’s General tab does not immediately refresh after selecting an asset catalog. To work around this, after selecting an asset catalog, navigate away from the General tab and then back. (26381374)

Scene Kit

Known Issues

  • SceneKit views (SCNView) do not render in Quick Look inside the Xcode Debugger when the current camera (SCNCamera) uses new effects such as color grading, color fringe, or saturation and contrast. (27653505)

Signing

Resolved Issues

  • When manually signing, Xcode requires your provisioning profile to contain all entitlements used by your default build configuration’s entitlements file. (28377448)

Known Issues

  • Inspector tooltips in Interface Builder are not available. (26664452)

  • The Xcode automatic signing system may fail to sign your app if you add your account or change your password while your project is open. As a workaround, close and reopen the project. (25627172)

  • When opening a project, Xcode only migrates the deprecated PROVISIONING_PROFILE setting to PROVISIONING_PROFILE_SPECIFIER when the setting is empty. (26281413)

  • Downloading profiles using the Download All Profiles button intermittently skips some profiles. As a workaround, use the developer website to download any missing profiles. (26412212)

  • Xcode may require a watch paired to your phone to be registered on the developer website even when developing an iOS only app. As a workaround, turn off your watch while developing, or develop using a different phone. (26885780)

  • Free provisioning accounts may experience issues launching apps on the watch for the first time. As a workaround, launch the app manually on the device and click Trust when the security sheet appears. (26629630)

  • Messages extensions signed with a personal team may fail to run on a device. As a workaround, on the device, go to Settings > General > Profiles & Device Management, tap on the profile name that authorized the app, and tap Trust. (26359174)

Simulator

Resolved Issues

  • Sticker Pack apps can be used in 32-bit simulators (iPhone 5, iPad Retina) in Xcode. (27830469)

  • Simulator no longer leaks memory when a simulated device is booted, rotated, or the scale is changed. (27673601)

Known Issues

  • The GameKit framework is missing from the SDK for the watchOS simulator. To work around this issue, develop for GameKit using a watchOS device which does include the framework. (27899791)

  • All connected host controllers are seen as the same controller for tvOS in Simulator. As a workaround, test multiple controller functionality on an AppleTV. (27511145)

  • There is no way to trigger Siri from Simulator even though Siri APIs are available in Simulator runtimes. Use an Apple TV to test usage of the Siri APIs. (25957692)

  • Keychain APIs may fail to work in the Simulator if your entitlements file doesn’t contain a value for the application-identifier entitlement. To work around this issue, add a user-defined build setting to your target named ENTITLEMENTS_REQUIRED and set the value to YES. This will cause Xcode to automatically insert an application-identifier entitlement when building. (28338972)

Source Editor

Resolved Issues

  • Xcode features provided via extensions now work more reliably. (28341722)

  • In Xcode 8.1, an XCSourceTextRange is half-open: It includes the character at the start position, and excludes the character at the end position. Previous versions of Xcode were inconsistent when translating from the internal format to an XCSourceTextRange instance. All Xcode Source Editor Extensions built against Xcode 8.0 will continue to get the previous inconsistent behavior for binary compatibility.

    An Xcode Source Editor Extension built against Xcode 8.1 that also needs to run in Xcode 8.0 can check the version of Xcode by comparing XCXcodeKitVersionNumber against the version listed in XcodeKit/XcodeKitDefines.h. (28131743)

Source Editor Extensions

Known Issues

  • Xcode Source Editor extensions don’t support adding Objective-C categories to XcodeKit classes. (26432410)

Swift

New Features

  • When Optional values are bridged to Objective-C objects, such as when an Optional is passed to an Objective-C API that takes nonnull id or when a [T?] array is bridged to an NSArray, the Swift runtime will now bridge the wrapped value if there is one. If a nil value is bridged, and the API does not accept a nil pointer, Swift will use NSNull to represent the nil value. (SE-0140)

  • All of Swift's standard number types now bridge to Objective-C as NSNumber instances. Structs such as CGRect, for which the NSValue class provides factory methods, now bridge to Objective-C as NSValue instances. (SE-0139)

  • Two types have been added to the Swift standard library: UnsafeRawBufferPointer and UnsafeMutableRawBufferPointer. They represent a non-owning view over a fixed region of memory (a buffer). They expose the underlying buffer as a Collection of UInt8 bytes, independent of the type of values held in that memory. This helps developers migrate to the UnsafePointer changes in Swift 3.0. For background, see the UnsafeRawPointer Migration Guide. In some cases, UnsafeRawBufferPointer provides a safe replacement for UnsafeBufferPointer<UInt8>. This is particularly useful for code that works with binary file formats and streaming I/O.

    A new withUnsafeBytes(of:) function exposes a value's in-memory representation as an UnsafeRawBufferPointer. This example copies a heterogenous struct into a homogeneous array of bytes:

    struct Header {
       var x: Int
       var y: Float
    }
     
    var header = Header(x: 0, y: 0.0)
    var byteBuffer = [UInt8]()
     
    withUnsafeBytes(of: &header) {
       (bytes: UnsafeRawBufferPointer) in byteBuffer += bytes
    }

    A new Array.withUnsafeBytes method exposes an array's underlying buffer as an UnsafeRawBufferPointer. This example copies an array of integers into an array of bytes:

    let intArray = [1, 2, 3]
    var byteBuffer = [UInt8]()
     
    intArray.withUnsafeBytes {
       (bytes: UnsafeRawBufferPointer) in byteBuffer += bytes
    }

    (SE-0138)

  • The macro __swift__ will be defined when importing C and Objective-C code into Swift. The value of this macro will have the form XYYZZ, where X is the major version of the language, YY is the minor version of the language (always two digits), and ZZ is the “patch” version (also two digits). For example, in Swift 3.0.1, __swift__ will have the value 30001. Note that this macro is not defined in the legacy Swift 2.3 compiler, nor was it defined in the initial release of Swift 3. (26921435)

Resolved Issues

  • An issue with @NSManaged properties being used to satisfy protocol requirements has been fixed. (SR-2673)

  • Linking LTO files compiled with Xcode 8 to LTO files compiled with a previous Xcode release will now work even if Objective-C class properties are in use. (28017126)

  • The C attribute swift_error(zero_result) is now handled correctly. (27985744)

  • Access checking for overrides and for members that satisfy protocol requirements has been fixed to more closely match the Swift language proposal that introduced private and fileprivate (SE-0025.) This resolves some crashes, but can result in errors for code that was accepted in Xcode 8.0. To keep Swift 3 code compatible with Xcode 8.0, use private for top-level classes and structs instead of fileprivate. (27820665)

  • Swift Evolution proposal SE-0107 states that UnsafePointer.withMemoryRebound(to:capacity:) should produce a const UnsafePointer, but in Swift 3.0 it produces an UnsafeMutablePointer. As a result, Swift 3.0 incorrectly accepts code in this form:

    let ptr: UnsafePointer<Int>
    ptr.withMemoryRebound(to: UInt.self, capacity: 1) {
       takesUInt($0) // this implicitly converts to a mutable pointer
    }

    For Swift 3.0.1, change the code to:

    ptr.withMemoryRebound(to: UInt.self, capacity: 1) {
       takesUInt(UnsafeMutablePointer(mutating: $0))
    }

    (28409842)

Known Issues

  • Extensions which make imported Objective-C generic classes conform to a Swift protocol can be miscompiled. This can result in a runtime crash in objc_retain or objc_msgSend when a class method is called generically through the protocol. (28873860)

    As a workaround, declare the protocol as @objc or wrap the class instance in a generic struct that implements the protocol.

  • When using generics and implicitly-unwrapped optionals, type inference can fail to unwrap the optional, leading to compiler errors for valid code. (28621624)

    As a workaround, explicitly unwrap the optional. For example, in the following valid code, the compiler gives an error because u is implicitly-unwrapped in the return statement.

    func compare<T: Comparable>(v: T, u: T!) -> Bool {
       return v < u
    }

    Work around the error by explicitly unwrapping u:

    func compare<T: Comparable>(v: T, u: T!) -> Bool {
       return v < u!
    }
  • Objective-C methods with empty selector pieces (i.e. a colon with no name before it) may cause the Swift 3 compiler to crash. As a workaround, rename the methods or remove them from the bridging header includes. If neither of those alternatives are possible, guard the method declaration. For example:

    #if !defined(__swift__) || __swift__ > 30001

    (28448188)

  • Lazy initialization using a constructor with defaulted parameters can fail with the message “type of expression is ambiguous without more context”. As a workaround, wrap the call to the constructor into a separate function if you want to use the defaulted parameters such as:

    struct Value {
       init(first: Int, second: Int? = 10) {}
    }
     
    class Test {
       static func createValue(first: Int) -> Value {
          return Value(first: first)
       }
     
       lazy var theValue = createValue(first: 5)
    }

    Calling the constructor without any of the parameters defaulted works as well. (28313602)

  • Some Objective-C methods in the SDKs may incorrectly annotate or assume a type to be nonnull rather than nullable. A type that Swift treats as a struct, such as NSURL (Foundation.URL) or NSDate (Foundation.Date), results in a run-time crash in a method with a name like bridgeFromObjectiveC; in other cases, it can lead to crashes or undefined behavior in user code. If you identify such a method, please file a report at bugreport.apple.com. As a workaround, add a trampoline function in Objective-C with the correct nullability annotations. For example, the following function will allow you to call FileManager'senumerator(at:includingPropertiesForKeys:options:errorHandler:) method with an error handler that accepts nil URLs:

    static inline NSDirectoryEnumerator<NSURL *> * _Nullable
     
    fileManagerEnumeratorAtURL(NSFileManager *fileManager, NSURL * _Nonnull url, NSArray<NSURLResourceKey> * _Nullable keys, NSDirectoryEnumerationOptions options, BOOL (^ _Nullable errorHandler)(NSURL * _Nullable errorURL, NSError * _Nonnull error)) {
         return [fileManager enumeratorAtURL:url includingPropertiesForKeys:keys options:options errorHandler:^(NSURL * _Nonnull errorURL, NSError * _Nonnull error) {
          return errorHandler(errorURL, error);
       }];
    }

    This function can be included in your bridging header (for an app or test target) or umbrella header (for a framework target). (27749845)

Testing

Known Issues

  • UI Recording in the Touch Bar only records tap interactions. (28500819, 28454674)

    To work around this, record the test and then change the generated code for the test to the desired type of interaction. For example, replace the call to tap with doubleTap to change from a single-tap to a double-tap. For possible interactions, see the documentation for XCUIElement.

  • UI tests may fail to run for apps written with Swift 2.3. (26680406)

  • Keystroke events issued by Xcode UI tests may be dropped if TextExpander is enabled. (25203671)

Xcode Server

Known Issues

  • Xcode Server reports the error “Verifying that Xcode is accessible” when Xcode is installed in a non-world-readable location other than /Applications.  Since the service makes use of role accounts to run various service daemons, those role accounts need to be able to read Xcode. As a workaround, place Xcode in the /Applications folder. (26920334)

Xcode 8.0

General

New Features

  • The clang static analyzer now checks for improper cleanup of synthesized instance variables in -dealloc methods. (6927496)

  • The indexing component has moved out of the Xcode process to an XPC service, providing the benefit of process isolation and accurate resource usage attribution. (24330820)

  • A fast scanner for unit tests is now available. The scanner will populate the Test navigator shortly after opening a project for the first time, eliminating the need to wait for indexing to parse all the unit test source files. It supports both Swift and Objective-C unit tests. (25716884)

Known Issues

  • Opening Xcode projects and workspaces stored in iCloud Drive, or changing source control branches for an open workspace or project stored in iCloud Drive, may sometimes cause Xcode to hang. Note that in macOS 10.12, your Documents and Desktop folders may optionally be iCloud Drive locations. (28212905)

Accessibility

Resolved Issues

  • On macOS 10.12, Xcode removes its custom motion animations from the user interface when the Reduce Motion setting is selected in System Preferences > Accessibility > Display. (26973957)

Address and Thread Sanitizers

New Features

  • Address Sanitizer is supported in Swift and can catch memory corruption errors that get triggered by using types such as UnsafeMutablePointer. (21888114)

  • The new thread sanitizer feature combines compiler instrumentation and runtime monitoring to help find and understand data races and other concurrency bugs in Swift and Objective-C. Thread sanitizer is supported on 64-bit macOS and 64-bit simulators. (19432893)

Apple LLVM Compiler and Low-Level Tools

Known Issues

  • Using a custom module map that contains system headers (directly or indirectly) can result in crashes of the LLVM or Swift compiler. For example, this can occur when using a module map with paths into the macOS SDK while building for iOS, or when using headers from the system /usr/include while building with any Xcode SDK.

    To work around this issue, make sure the system headers mentioned in the module map or included by custom headers are always found in the current target's SDKROOT. (26866326)

  • Older versions of libobjc cannot fully handle the runtime metadata provided by the compiler for class properties. Therefore, if your deployment target is older than OS X 10.11 or iOS 9, some of this metadata will be absent. It is still safe to use class properties in projects deploying to newer OS versions, and the accessor methods will still show up in the runtime metadata. If you aren't using the Objective-C runtime to get information about class properties, you don't need to worry about this issue. (25616128)

  • Trying to link with LTO files compiled with Xcode 8 and files compiled with a previous Xcode release may fail if Objective-C class properties are in use. (28017126)

  • Activity and trace messages normally visible in LLDB thread summaries and thread detailed information is absent when debugging processes running on beta versions of macOS, iOS, tvOS, or watchOS. (26370425)

  • If any Swift code contains a private func == definition, LLDB fails to evaluate expressions in a Swift context with the error: binary operator '==' cannot be applied to two 'Int' operands. To work around this issue, make any == overloads in your program non-private. (27015195)

  • The new LLVM-based otool(1) exits non-zero on the first error it encounters for the files on the command line. This includes treating non-object files as errors. This differs from the old otool(1), available as otool-classic(1), which processes all files on the command line even if some have errors and does not treat non-object files as an error but as a warning. (26828015)

Asset Catalog

Known Issues

  • Applications compiled with Xcode 8 and a deployment target of iOS 7 may crash at launch with the following assertion:

    Assertion failed: (maxCountIncludingZeroTerminator > 0 && tokenCount < maxCountIncludingZeroTerminator), function CUIRenditionKeyCopy, file /SourceCache/CoreUI/CoreUI-232.4/CoreTheme/ThemeStorage/CUIThemeRendition.m, line 185.

    To work around this issue, update the deployment target to iOS 8.0 or later, or add a single image to the asset catalog that has at least five attributes specified across the image set, such as:

    • scale (1x, 2x, 3x)

    • idiom (add iPad,iPhone, and a universal asset)

    • direction (left to right, right to left)

    • width/height class (any & compact, and so forth)

    • memory (add a 1 GB asset)

    • graphics (add a Metal 1v2 asset)

    It is not necessary to use the image in your code or to add all of these attributes. (27852391)

Building and Linking

New Features

  • The PNG compression build settings Compress PNG Files and Remove Text Metadata From PNG Files are available for macOS in addition to iOS, watchOS, and tvOS. For macOS, both settings are off by default. (24638927)

  • The build setting ENABLE_ADDRESS_SANITIZER controls whether the address sanitizer is enabled across both the clang and swiftc compilers. Previously only CLANG_USE_ADDRESS_SANITIZER existed; that setting is now subordinate to ENABLE_ADDRESS_SANITIZER and should not be used by itself. If a project was previously using CLANG_USE_ADDRESS_SANITIZER as a build setting to enable the address sanitizer separate from the scheme option, then ENABLE_ADDRESS_SANITIZER should now be used instead. (24912445)

  • Xcode takes build settings set in xcconfig files into account when suggesting updates to your build settings. (13433596)

  • xcconfig files support conditional inclusion of other xcconfig files, using the syntax #include? instead of the usual #include (which still generates a warning, as before, if the file is missing). (11003005)

  • The static analyzer check for nullability violations now supports both aggressive and less aggressive levels of checking. The more-aggressive level checks for nullability violations in all calls and is enabled by default for new projects. The less-aggressive level checks for nullability violations in calls to project headers but not system headers. The less-aggressive level is enabled by default for existing projects. To turn on the more-aggressive level for existing projects, select "Yes (Aggressive)" for "Misuse of ‘nonnull’" in the Static Analyzer - General Issues section of the target build settings. (25120516)

  • The development team used for signing is now stored in a new build setting, DEVELOPMENT_TEAM. This allows overriding the development team using xcconfig files. As a result, the format of the new PROVISIONING_PROFILE_SPECIFIER build setting has changed. The old format, which included a team ID, is still supported, but it now needs to contain only a provisioning profile name. (27082795)

  • If your CODE_SIGN_ENTITLEMENTS value is conditionalized per SDK, add a setting for the appropriate simulator SDK(s) explicitly. Previous versions of Xcode fell back to the iOS SDK’s value; this is no longer the case. (26923346)

  • When the Enable Testability build setting is enabled, Xcode 8 will pass -export_dynamic to the linker to preserve all global symbols for testing. This effectively overrides dead code stripping, which can expose link failures from unused functions that reference undefined symbols. If necessary, disabling testability will allow the link to proceed without source changes. (27684883)

  • xcodebuild now supports a -quiet flag to suppress output other than errors and warnings. (5732994)

  • In macOS 10.12 and later, Xcode cleans up stale derived data, precompiled headers, and module caches. (23282174)

Certificates and Profiles

Resolved Issues

  • In Developer ID provisioning profiles, the value of the com.apple.developer.icloud-container-environment entitlement has changed from an array to a string. (26722546)

  • When exporting an app with Developer ID, Xcode will automatically generate Developer ID provisioning profiles for any bundles embedded in the app. (26827710)

Known Issues

  • Developer ID apps using profiles will not work on versions of OS X prior to 10.10. You can work around this issue by explicitly installing the profile before running the app. (26013718)

  • Xcode 8 does not automatically copy the aps-environment entitlement from provisioning profiles at build time. This behavior is intentional. To use this entitlement, either enable Push Notifications in the project editor’s Capabilities pane, or manually add the entitlement to your entitlements file. (28076333)

Code Signing

Resolved Issues

  • Xcode does not require code signing for iOS frameworks, and will skip signing a framework if a team is not specified. Frameworks should be signed when copied into the hosting product (using the Code Sign on Copy flag in a Copy Files build phase). (26892618)

Color Management

Resolved Issues

  • Fixed a crash opening documents using a pattern color with NSPatternColorSpace. (26964970)

Command Line

New Features

  • The Swift Package Manager tool for managing the distribution of Swift code is available on the command line. Help for the Swift Package Manager can be found by running swift package --help in Terminal. (25582703)

Core Data

New Features

  • Xcode automatically generates classes or class extensions for the entities and properties in a Core Data data model. Automatic code generation is enabled and disabled on an entity by entity basis, and is enabled for all entities in new models that use the Xcode 8 file format. This feature is available for any data model that has been upgraded to the Xcode 8 format. You specify whether Xcode generates Swift or Objective-C code for a data model using the data model’s file inspector.

    When automatic code generation is enabled for an entity, Xcode creates either a class or class extension for the entity as specified in the entity's inspector: the specified class name is used and the sources are placed in the project’s Derived Data. For both Swift and Objective-C, these classes are directly usable from the project’s code. For Objective-C, an additional header file is created for all generated entities in your model. The header file name conforms to the naming convention “DataModelName+CoreDataModel.h”.

    The Xcode attribute inspector also allows a choice of whether to generate scalar or object properties. New attributes default to generating scalar properties where appropriate. For attributes that previously relied on filling in class information after code was manually generated (for example, transformable attributes and transient attributes with an undefined attribute type), specify the class to use in the attribute’s declaration directly in the attribute inspector. (22223273)

Debugging

New Features

  • Debugging mixed Objective-C and Swift projects has been improved by displaying Swift instance variables even when showing Objective-C references to Swift types. (24083219)

  • Memory graph debugging is available for WatchKit extensions. (26563396)

  • In addition to the Xcode console, Terminal can be used for macOS process input and output while debugging. Open the scheme editor to edit your scheme’s Run action and then select the Use Terminal option in the Options tab. (23565724)

  • LLDB fully supports the Swift 3 language and includes numerous quality improvements to make Swift debugging more accurate and reliable. Note that when debugging Swift 2.3 code an earlier version of LLDB will be used, and most new LLDB features will not be available. (22509661)

  • Stepping into a specific function in a complex line of code is much easier. Consider the following example:

    Resolved Issues(bar(), baz())

    Previously, stepping into Resolved Issues() required stepping into and out of bar() and baz(). Now the sif alias makes this easy. The command sif Resolved Issues will step through other functions until it reaches the named target. If the expected target isn’t reached, it provides a safeguard by stopping after returning from the current scope. (24528770)

  • Xcode 8 now isolates LLDB as a distinct process. This is largely transparent but has the following implications:

    • In the event of an unrecoverable failure while debugging, Xcode will be unaffected aside from closing the debug session.

    • Multiple debugger versions can be used simultaneously. Projects containing Swift 2.3 code will use an earlier corresponding LLDB, and when working with an open source Swift toolchain, the included LLDB will be used.

    (23418627)

  • LLDB now supports and correctly displays the value of thread-local variables. (7796742)

  • LLDB documentation has been significantly updated:

    • A new LLDB Debugging Guide is available in Xcode help.

    • LLDB’s built-in help text has been overhauled for clarity and consistency.

    • When no help is available via help <topic> in LLDB, alternative suggestions are displayed.

    • Command aliases can now have custom help text, and several of the key built-in aliases take advantage of this facility.

    (24868841)

  • Expressions that can be trivially corrected using compiler fix-its are automatically fixed and executed. This ensures that LLDB doesn’t get in your way for something as simple as a missing semicolon or the wrong style of indirection in Objective-C; or the need to unwrap a value in Swift. (25351938)

  • Expressions in LLDB support an even wider array of scenarios. Declaring and capturing Objective-C blocks and C++ lambdas now works as expected, and declaring C and C++ functions is now possible using the new --top-level (or -p) option on the expression command. (22509903)

  • Two new command aliases make it easy to examine C-style arrays. The commands parray and poarray behave like their counterparts p and po when formatting each element of the specified array. The length of the array must be specified first, followed by a pointer to the array. The usual LLDB conveniences for specifying arguments using the result of expressions can be used for the length—for example, parray `argc` argv when stopped in a C, C++, or Objective-C main function. (12691162)

  • Processes built with thread sanitizer enabled will display relevant information when issues are detected while debugging with LLDB. (23956680)

Resolved Issues

  • Debugging a Notification extension works with the normal extension debugging workflow in Xcode. (23487932)

  • Debugging with address sanitizer does not result in a runtime error regarding dyld inserting the ASan library. (23805032)

  • Fixed a crash for macOS apps running with thread sanitizer when profiling from the Memory gauge. (26275485)

  • The view debugger shows the debug description for views in the inspector. (23976841)

  • The view debugger shows the frame for views in the size inspector. (24314615)

  • The view debugger functions normally when debugging on the iOS 8 simulator. (25802025)

  • Resolved an issue where view debugging could fail when not using auto layout, due to an unhandled assertion in an underlying system framework. (25311044)

  • Resolved stability issues with debugging extensions or watch apps in the simulator. (25338888)

Deprecations

  • Debugger() and DebugStr() are deprecated and the scheme editor no longer provides the option to enable these functions. If your project uses these functions, enable them by setting the environment variable USERBREAK with a value of 1. (24631170)

Device Management

New Features

  • You must unlock devices when first connecting them to Xcode in order to use them for development. (25771635)

Instruments

Known Issues

  • Instruments can't find the symbols downloaded for Apple Watch. As a workaround, find the device support folder for your Apple Watch version (it will be inside ~/Library/Developer/Xcode/watchOS DeviceSupport/), create an empty Info.plist file inside this folder, and restart Instruments. (27996340)

  • The Instruments Leaks template fails to report data against Swift apps with a Release configuration, because this configuration enables Whole Module Optimization by default. To work around this issue: if you're targeting a Swift app, temporarily turn off Whole Module Optimization when using either the Leaks template in Instruments or the Memory Graph Debugger in Xcode. (27906876)

Deprecations

  • The Automation instrument has been removed from Instruments. Use Xcode’s UI Testing instead. (26761665)

Interface Builder

New Features

  • Interface Builder makes it easier to migrate to auto layout by no longer generating implicit constraints for views without constraints. (13728545, 24274870)

  • The size inspector now displays frame coordinates with greater precision, and can accept fractional point values on Retina displays for iOS. (8895377)

  • Storyboard and xib files support smooth zooming across iOS, tvOS, and watchOS, as well as editing at any zoom level. When using a mouse, operating the scroll wheel while holding down the option key allows you to zoom in and out. (5215027, 9635866, 11579591, 15011038, 21256576, 23379420)

  • A completely redesigned workflow for working with trait variations (for example, size classes), supports designing UI in terms of a real device size rather than by using intentionally abstract rectangles. Combined with a new mode for quickly introducing variations, it’s easier than ever to see what your UI looks like across multiple devices, orientations, and adaptations like Slide Over and Split View on iPad. (16901225, 23804474, 24012599)

  • Creating an @IBAction method by control-dragging from Interface Builder to a Swift 3 source file includes an underscore before the sender parameter, causing the corresponding Objective-C selector to match Swift 2 behavior. Converting to Swift 3 syntax modifies @IBAction methods by adding an underscore, preserving connections in existing IB documents. (26120871)

  • The Notes field in the Identity inspector now has "Comment For Localizer" placeholder text to more clearly indicate that it is included in an XLIFF export. (26802029)

  • Xcode 8 removes the ability to configure views without constraints with frame varying per size class. Views without constraints may look different after compiling with Xcode 8 when switching size classes at runtime. Going forward, use constraints and autoresizing masks with the device bar to achieve the desired layout. (25894544)

  • The canvas in Interface Builder renders visual interactions between iOS views as they appear at runtime, including accurate compositing of UIVisualEffectView. Designable views can now visually interact with their subviews. Rendering performance is significantly improved for tvOS documents. (21922006)

  • Interface Builder supports customizing UI elements for Dark interface style on tvOS and previewing in the assistant editor. This support is enabled by default for new xib and storyboard files; it can be enabled for existing documents by selecting the Uses Trait Variations option in the Identity inspector. (23343849)

  • Interface Builder supports colors in the Display P3 color space. In the system color panel, select RGB or HSB sliders, click the gear menu to the right of the popup button, and choose Display P3 from the list. (23612133)

  • The UI for customizing inspector properties for iOS size classes is improved, and defaults to the configuration that is currently active in the canvas. (26123851)

  • Xcode 8 provides numerous accessibility improvements, including VoiceOver enhancements to the design canvas, inspectors, document outline, and object library. (5306382)

  • While the canvas is varying for traits (indicated by a blue bottom bar) and has focus, the Delete key uninstalls the selected objects only for the current configuration. If the document outline has focus, or when the canvas is not in varying mode, the Delete key removes the selected objects from the document, affecting all configurations. (26153578)

  • Color values in Interface Builder documents correctly use color space during rendering and compilation. Earlier versions of Xcode mishandled color spaces saved in iOS and tvOS documents. Xcode 8 converts existing colors in a way that preserves their perceptual appearance on a device, and updates either the color space or component values in the source document as appropriate. (7645087)

Resolved Issues

  • Constraint constants with fractional (non-integer) values can now be configured in Interface Builder. (15963933)

  • Constraints to a view are now preserved when the view is embedded in a new view, or dragged to within a new superview. (9666331)

  • Storyboard and xib files can be scrolled while dragging objects or scenes, and during control-dragging to create connections. Dragging to the edge of the canvas activates autoscrolling. (25221374, 25631320)

  • Interface Builder's design canvas draws correctly when layer-backing is enabled in macOS xib and storyboard documents. This includes canvas decorations such as resize knobs, selection indicators, bounds rectangles, constraints, and segue arrows. (5565950)

  • Fixed a crash when navigating away from an Interface Builder document that uses custom fonts and designable views. (17237787)

  • NSBox properties that are inapplicable for custom box and separator lines are excluded from inspectors, warnings, and saved documents. This includes a localizable title for separator lines that was unintentionally included in XLIFF output. (5081354, 9939692, 14994467, 23877301)

  • Using a custom font in UILabel, UITextField, or UITextView with size classes enabled now correctly encodes the font for use at runtime. (18535469)

  • Xcode records custom font names once per document, rather than once for each use in a document. (18389741)

Known Issues

  • Inspector tooltips in Interface Builder are not available.

Localization

New Features

  • For projects with localizations in more than one language, Xcode automatically turns on the static analyzer check for missing localizability. (22807459)

Resolved Issues

  • XLIFF export no longer includes accessibilityIdentifier strings configured in Interface Builder. (24548071)

Logging

New Features

  • Logging for simulated key presses includes the glyph representations for modifier keys, as well as the glyph and symbol name for constants starting with XCUIKeyboardKey. (27374182)

Resolved Issues

  • Unified Logging is now supported for apps uploading to TestFlight and the App Store. (27794355)

Metal Support

New Features

  • A new target type for Metal libraries enables creating new projects, or new targets in existing projects, for platforms that support Metal. Targets of this type only compile Metal source files and produce Metal libraries. A Metal library produced in this manner can be added to the Copy Bundle Resources build phase of another target to make the Metal content available to that target's products. (17877026)

Objective-C and C++

New Features

  • Objective-C now supports class properties, which interoperate with Swift type properties. They are declared as @property (class) NSString *someStringProperty;, and are never synthesized. (23891898)

  • C++ now supports the thread_local keyword, which declares thread-local storage (TLS) and supports C++ classes with non-trivial constructors and destructors. (9001553)

  • Incremental Link-Time Optimization (LTO) has been added and is a major redesign of the existing monolithic LTO mode. Incremental LTO addresses the three main limitations of monolithic LTO by making it parallel, memory lean, and incremental. (22252706)

Playgrounds

New Features

  • The playground video tag now supports remote URLs. (24886083)

Resolved Issues

  • The first link included in a playground markup comment does not have its hit target reduced to the beginning of the linked text. (24920637)

  • Live views for iOS playgrounds display retina views on Macs with retina displays. (26945081)

  • The editor's Add Documentation command is enabled when editing a playground. (27395238)

Projects

New Features

  • Xcode 8 contains a project template for a cross-platform SpriteKit game. When you create a project from this template, you can choose which platforms should be supported (iOS, macOS, tvOS, watchOS). The resulting project will contain a target for each selected platform and will factor out content that is appropriate to be shared between all platforms. Shared content includes the primary SKScene subclass, sks files, and the main asset catalog. Platform-specific content is created for each supported platform including app delegates, view controllers, and so forth. (26543360)

Resolved Issues

  • The "Embed Binaries" section of the target editor correctly adds new embedded binaries. (27631378)

  • Xcode correctly embeds or links frameworks across projects without requiring you to set up a direct reference between the project that produces the framework and the project that embeds or links it. (27631386)

  • Changes made to projects from outside Xcode (for instance, from Git) do not cause Xcode to select a different active scheme. (16762297)

Scripting Support

New Features

  • Xcode 8 provides completely rewritten AppleScript support. A new scripting dictionary provides the ability to automate Xcode workflows. New functionality includes, for example, the ability to perform "run" and "test" actions. Some previous functionality, such as manipulating files and groups in a workspace, has been curtailed for enhanced reliability. Open Script Editor.app and select File > Open Dictionary to access the Xcode scripting library.

    Xcode scripts can be used in Automator workflows with the Run Script command. (22819339)

Signing Assets

New Features

  • The signing system has been rewritten to include a new mode for automatically managing signing assets, in addition to a dedicated manual mode where the profiles for the target must be explicitly selected. When automatically managing signing assets, Xcode will create signing certificates, update app IDs, and create provisioning profiles. For manual mode, only custom created profiles can be selected and Xcode will not modify or create any signing assets.

    Xcode now encodes profiles in the target using the PROVISIONING_PROFILE_SPECIFIER build setting. This setting allows specifying both the team ID and the name or identifier of the profile. (23992778)

Simulator

Resolved Issues

  • UIContentSizeCategoryDidChangeNotification is delivered as expected in the iOS 10.0 Simulator runtime. (25303105)

  • SKVideoNode is usable in the iOS and tvOS Simulator Runtimes. (26433285)

Known Issues

  • The GameKit framework is missing from the SDK for the watchOS simulator. However, the framework is present for watchOS devices, so you can still do development of GameKit apps for watchOS on devices. (27899791)

Source Control

New Features

  • Xcode now assumes that Git repositories with “core.precomposeunicode” unset or set to false are using macOS canonical decomposition normalization for Unicode filenames. This may cause repositories that have this unset or set to false to have trouble with some Unicode file names if the filename normalization in the repository was done on another platform. (26861162)

    To work around this issue, make sure the configuration for Git repositories has “core.precomposeunicode” set to true. This will be the case for any repository created with the Git tools that ship with Xcode. Only leave it unset or set to false for compatibility with repositories that have Unicode filenames using macOS canonical decomposition normalization.

Source Editor

New Features

  • Xcode 8 adds support for Xcode source editor extensions. Application extensions provide additional commands in the Xcode Editor menu. These extensions can manipulate both text and selections. To create them, use the new Xcode Source Editor Extension target template in the macOS Application Extensions section when creating a project. (23194974)

Known Issues

  • To use the Editor's Comment/Uncomment Selection and Add Documentation commands—as well as other installed Xcode Extensions—on OS X 10.11, launch Xcode and install additional system components, then restart your Mac. (26106213)

Swift

New Features

  • The version of Swift 2 (2.3) used in Xcode 8 is very close to the version used in Xcode 7.3.1. However, it has been updated for the newer SDKs, and therefore is not compatible with Swift frameworks compiled in Xcode 7.3.1. Distributing binary Swift frameworks remains unsupported in Xcode 8. (25680392)

  • For information on migrating from Swift 2 to Swift 3, see the Swift Migration Guide.

  • When a Swift program traps at runtime due to an unexpected null value, the error message reports the source location of the ! operator or implicit unwrapping in the user's source code. (26919123)

  • Argument labels have been removed from Swift function types. Instead, they are part of the name of a function, subscript, or initializer. Calls to a function or initializer, or uses of a subscript, still require argument labels, as they always have:

    func doSomething(x: Int, y: Int) {}
    doSomething(x: 0, y: 0)   // argument labels are required

    However, unapplied references to functions or initializers no longer carry argument labels. For example:

     let f = doSomething(x:y:)   // inferred type is now (Int, Int) -> Void

    Additionally, explicitly-written function types can no longer carry argument labels, although one can still provide a parameter name for documentation purposes using the _ in the argument label position:

    typealias CompletionHandler =
      (token: Token, error: Error?) -> Void  // error: function types cannot have argument labels
     
    typealias CompletionHandler =
      (_ token: Token, _ error: Error?) -> Void  // error: okay: names are for documentation purposes

    (SE-0111)

  • Objective-C APIs using id now import into Swift as Any instead of as AnyObject. Similarly, APIs using untyped NSArray and NSDictionary import as [Any] and [AnyHashable: Any], respectively. (SE-0116)

  • Any is now accepted as a valid "sender" type for IBAction methods. (27853737)

  • Since id now imports as Any rather than AnyObject, you may see errors where you were previously performing dynamic lookup on AnyObject. For example:

    guard let fileEnumerator = FileManager.default.enumerator(atPath: path) else {
      return
    }
    for fileName in fileEnumerator {
      if fileName.hasSuffix(".txt") { // error: value of type ‘Element’ (aka ‘Any’) has no member hasSuffix
       print(fileName)
      }
    }

    The fix is to either cast to AnyObject explicitly before doing the dynamic lookup, or force cast to a specific object type:

    guard let fileEnumerator = FileManager.default.enumerator(atPath: path) else {
      return
    }
    for fileName in fileEnumerator {
      if (fileName as AnyObject).hasSuffix(".txt") {// cast to AnyObject
       print(fileName)
      }
    }

    (27639935)

  • Closure parameters are non-escaping by default, rather than explicitly being annotated with @noescape. Use @escaping to indicate that a closure parameter may escape. @autoclosure(escaping) is now written as @autoclosure @escaping. The annotations @noescape and @autoclosure(escaping) are deprecated. (SE-0103)

  • The @noreturn attribute on function declarations and function types has been removed, in favor of an empty Never type:

    @noreturn func fatalError(msg: String) { ... } // old
    func fatalError(msg: String) -> Never { ... }  // new
     
    func performOperation<T>(continuation: @noreturn T -> ()) { ... } // old
    func performOperation<T>(continuation: T -> Never) { ... }     // new

    (SE-0102)

  • Xcode imports Objective-C protocol-qualified classes (for example Class <NSCoding>) into Swift as protocol type values (NSCoding.Type). (15101588)

  • The types UnsafePointer, UnsafeMutablePointer, AutoreleasingUnsafeMutablePointer, OpaquePointer, Selector, and NSZone now represent non-nullable pointers—that is, pointers that are never nil. A nullable pointer is now represented using Optional, for example,UnsafePointer<Int>?.

    For types imported from C, non-object pointers (such as int *) now have their nullability taken into account:

    • A pointer marked as _Nonnull, or within an NS_ASSUME_NONNULL_BEGIN/_END block, is imported as a non-optional value. Example: NSInteger * _Nonnull is imported as UnsafeMutablePointer<Int>.

    • A pointer marked as _Nullable is imported as an optional value. Example: NSInteger * _Nullable is imported as UnsafeMutablePointer<Int>?.

    • A pointer marked as _Null_unspecified, or an unannotated pointer outside of any NS_ASSUME_NONNULL_BEGIN/_END block, is imported as an implicitly-unwrapped optional value. Example: NSInteger * _Null_unspecified is imported as UnsafeMutablePointer<Int>!.

      The Swift standard library has been adjusted to match.

      One possible area of difficulty is passing a nullable pointer to a function that uses C variadics. Swift will not permit this directly, so as a workaround please use the following idiom to pass it as a pointer-sized integer value instead:

      Int(bitPattern: nullablePointer)

      The "pointee" types of imported pointers (for example, the id in id *) are no longer assumed to always be _Nullable even if annotated otherwise. However, an implicit or explicit annotation of _Null_unspecified on a pointee type is still imported as Optional. (SE-0055)

  • The "Ref" forms of CF type names have been removed from Swift. For example, use CFString instead of CFStringRef.

    One exception is if there are types named both "Resolved Issues" and "Resolved IssuesRef," where "Resolved IssuesRef" is a Core Foundation type. In this case, both types will continue to be imported as they always have. (16888940)

  • Condition clauses in if, guard, and while statements use a more regular syntax. Prefix each pattern or optional binding with case or let, respectively, and separate all conditions with “,” instead of “where”. For example, the code previously written as:

    if let a = a, b = b where a == b {}

    is now written as:

    if let a = a, let b = b, a == b {}

    (SE-0099)

  • Nested generic functions can now capture bindings from the environment. For example:

    func outer<T>(t: T) -> T {
      func inner<U>(u: U) -> (T, U) {
        return (t, u)
      }
      return inner(u: (t, t)).0
    }

    (22051279)

  • Function parameters now have consistent labeling across all function parameters. With this update the first parameter declarations will now match the existing behavior of the second and later parameters.

    Code that was previously written as:

    func Resolved Issues(x: Int, y: Int) {}
    Resolved Issues(1, y: 2)
     
    func bar(a a: Int, b: Int) {}
    bar(a: 3, b: 4)

    should now be written as:

    func Resolved Issues(_ x: Int, y: Int) {}
    Resolved Issues(1, y: 2)
    func bar(a: Int, b: Int) {}
    bar(a: 3, b: 4)

    (SE-0046)

  • The Objective-C selectors for the getter or setter of a property can now be referenced with #selector. For example:

    let sel1 = #selector(getter: UIView.backgroundColor) // sel1 has type Selector
    let sel2 = #selector(setter: UIView.backgroundColor) // sel2 has type Selector

    (SE-0064)

  • Collection subtype conversions and dynamic casts now work with protocol types. For example:

    protocol P {}; extension Int: P {}
    var x: [Int] = [1, 2, 3]
    var p: [P] = x
    var x2 = p as! [Int]
  • The hasPrefix and hasSuffix functions now consider the empty string to be a prefix and suffix of all strings. (SR-2131)

  • The None members of imported NS_OPTIONS option sets are marked as unavailable when they are imported. Use [] to make an empty option set, instead of a None member.

  • Generic typealiases are now supported. For example:

    typealias StringDictionary<T> = Dictionary<String, T>
    typealias IntFunction<T> = (T) -> Int
    typealias MatchingTriple<T> = (T, T, T)
    typealias BackwardTriple<T1, T2, T3> = (T3, T2, T1)
  • The @noescape attribute has been extended to be a more general type attribute. You can now declare values of @noescape function type. You can now also declare local variables of @noescape type, and use @noescape in typealiases. For example, the following is now valid code:

    func apply<T, U>(@noescape f: T -> U,
               @noescape g: (@noescape T -> U) -> U) -> U {
      return g(f)
    }
  • Curried function syntax has been removed, and now produces a compile-time error.

  • Generic signatures can now contain superclass requirements with generic parameter types. For example:

    func f<Resolved Issuesd : Chunks<Meat>, Meat : Molerat>(f: Resolved Issuesd, m: Meat) {}
  • Catch blocks in rethrows functions can now throw errors. For example:

    func process(f: () throws -> Int) rethrows -> Int {
      do {
        return try f()
      } catch is SomeError {
        throw OtherError()
      }
    }
  • Throwing closure arguments of a rethrowing function can now be optional. For example:

    func executeClosureIfNotNil(closure: (() throws -> Void)?) rethrows {
      try closure?()
    }
  • The FloatingPoint protocol has been expanded to include most IEEE 754 required operations. A number of useful properties have been added to the protocol as well, representing quantities like the largest finite value or the smallest positive normal value (these correspond to the macros such as FLT_MAX defined in C).

    While most of the changes are additive, there are four changes that will impact existing code:

    • The % operator is no longer available for FloatingPoint types. The new method formTruncatingRemainder(dividingBy:) provides the old semantics if they are needed.

    • The static property .NaN has been renamed .nan.

    • The static property .quietNaN was redundant and has been removed. Use .nan instead.

    • The predicate isSignaling has been renamed isSignalingNaN.

    (SE-0067)

  • Most keywords are now allowed in member references. This allows the use of members after a dot without backticks. For example, "Resolved Issues.default." (SE-0071)

  • A key-path can now be formed with #keyPath. For example:

    person.valueForKeyPath(#keyPath(Person.bestFriend.lastName))

    (SE-0062)

  • The location of the inout attribute has been moved to after the : and before the parameter type. For example, code previously written as:

    func Resolved Issues(inout x: Int) {
    }

    should now be written as:

    func Resolved Issues(x: inout Int) {
    }

    (SE-0031)

  • The #line directive (which resets the logical source location for diagnostics and debug information) has been renamed to #sourceLocation. (SE-0034)

  • A declaration marked as private can now only be accessed within the lexical scope it is declared in (essentially the enclosing curly braces {}). A private declaration at the top level of a file can be accessed anywhere in that file, as in Swift 2. The access level formerly known as private is now called fileprivate. (SE-0025)

  • The compiler now provides an error when enum elements are accessed as instance members in instance methods. For example:

    enum Color {
     case red, green, blue
     
     func combine(with color: Color) -> Color {
      return red
     }
    }

    In Swift 2.2, this is valid code. The correct way to write this in Swift 3 is:

    return .red

    (SE-0036)

  • It is now possible to declare variables in multiple patterns in cases. (SE-0043)

  • Initializers are now inherited even if the base class or derived class is generic:

    class Base<T> {
      let t: T
     
      init(t: T) {
        self.t = t
      }
    }
     
    class Derived<T> : Base<T> {
      // init(t: T) is now synthesized to call super.init(t: t)
    }

    (17960407)

  • where clauses are now specified after the signature for a declaration but before its body. For example, before:

    func anyCommonElements<T : SequenceType, U : SequenceType
      where T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element>
      (lhs: T, _ rhs: U) -> Bool
    {
      ...
    }

    and after:

    func anyCommonElements<T : SequenceType, U : SequenceType>(lhs: T, _ rhs: U) -> Bool
      where T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element
    {
      ...
    }

    The old form is still accepted for compatibility, but will eventually be rejected. (SE-0081)

  • The NSError type is bridged to the Swift Error protocol type (formerly called ErrorProtocol in Swift 3 and ErrorType in Swift 2) in Objective-C APIs, much like other Objective-C types are bridged to Swift (for example, NSString being bridged to String). For example, the UIApplicationDelegate method application(_:didFailToRegisterForRemoteNotificationsWithError:) changes from accepting an NSError argument:

      optional func application(_ application: UIApplication,
      didFailToRegisterForRemoteNotificationsWithError error: NSError)

    to accepting an Error argument:

    optional func application(_ application: UIApplication,
      didFailToRegisterForRemoteNotificationsWithError error: Error)

    Additionally, error types imported from Cocoa and Cocoa Touch maintain all of the information in the corresponding NSError, so it is no longer necessary to catch let as NSError to extract (for example) the user-info dictionary. Specific error types also contain typed accessors for their common user-info keys. For example:

      catch let error as CocoaError where error.code == .fileReadNoSuchFileError {
        print("No such file: \(error.url)")
      }

    Swift-defined error types can provide localized error descriptions by adopting the new LocalizedError protocol. For example:

      extension HomeworkError : LocalizedError {
        var errorDescription: String? {
          switch self {
            case .forgotten: return NSLocalizedString("I forgot it")
            case .lost: return NSLocalizedString("I lost it”)
            case .dogAteIt: return NSLocalizedString("The dog ate it”)
      } }
    }

    Similarly, the new RecoverableError and CustomNSError protocols allow additional control over the handling of the error. (SE-0112)

  • The protocol<...> composition construct has been removed. In its place, an infix type operator & has been introduced.

    let a: Resolved Issues & Bar
    let b = value as? A & B & C
    func Resolved Issues<T : Resolved Issues & Bar>(x: T) { … }
    func bar(x: Resolved Issues & Bar) { … }
    typealias G = GenericStruct<Resolved Issues & Bar>

    The empty protocol composition, the Any type, was previously defined as being protocol<>. This has been removed from the standard library and Any is now a keyword with the same behavior. (SE-0095)

  • Bridging conversions are no longer implicit. The conversion from a Swift value type to its corresponding object can be forced with as—for example, string as NSString. Any Swift value can also be converted to its boxed id representation with as AnyObject. (SE-0072)

  • Attributes changed from using = in parameters lists to using :, aligning with function call syntax. (SE-0040)

  • The dynamicType keyword has been removed from Swift. In its place a new primitive function type(of:) has been added to the language. Existing code that uses the .dynamicType member to retrieve the type of an expression should migrate to this new primitive. Code that is using .dynamicType in conjunction with sizeof should migrate to the MemoryLayout structure provided by proposal SE-0101. (SE-0096)

  • The syntax for adding new operators has changed significantly. The new language model uses a more semantic model based on named precedence groups rather than magic numbers. This only affects declaring new operators such as >>> and not adding new overloads of existing operators such as ==. (SE-0077)

  • To clarify the role of *LiteralConvertible protocols, they have been renamed to ExpressibleBy*Literal. No requirements of these protocols have changed. (SE-0115)

  • Function parameters with default arguments must now be specified in declaration order. A call site must always supply the arguments it provides to a function in their declared order:

    func requiredArguments(a: Int, b: Int, c: Int) {}
    func defaultArguments(a: Int = 0, b: Int = 0, c: Int = 0) {}
     
    requiredArguments(a: 0, b: 1, c: 2)
    requiredArguments(b: 0, a: 1, c: 2) // error
    defaultArguments(a: 0, b: 1, c: 2)
    defaultArguments(b: 0, a: 1, c: 2) // error

    Arbitrary labeled parameters with default arguments may still be elided, as long as the specified arguments follow declaration order:

    defaultArguments(a: 0) // ok
    defaultArguments(b: 1) // ok
    defaultArguments(c: 2) // ok
    defaultArguments(a: 1, c: 2) // ok
    defaultArguments(b: 1, c: 2) // ok
    defaultArguments(c: 1, b: 2) // error

    (SE-0060)

  • let is no longer accepted as a parameter attribute for functions. The compiler provides a fixit to remove it from the function declaration. (SE-0053)

  • var is no longer accepted as a parameter attribute for functions. The compiler provides a fixit to create a shadow copy in the function body. For example, the code previously written as:

    func Resolved Issues(var x: Int) {
    }

    should now be written as:

    func Resolved Issues(x: Int) {
      var x = x
    }

    (SE-0003)

  • Classes declared as public can no longer be subclassed outside of their defining module, and methods declared as public can no longer be overridden outside of their defining module. To allow a class to be externally subclassed or a method to be externally overridden, declare them as open, which is a new access level beyond public.

    Imported Objective-C classes and methods are now all imported as open rather than public. Unit tests that import a module using a @testable import will still be allowed to subclass public classes and override public methods. (SE-0117)

  • The domain property of an NSError containing an error thrown from Swift now includes the module name of the type, matching the constant shown in the generated header. (SR-700)

  • Methods whose names start with init are no longer considered to be part of the Objective-C "init" method family. (25759260)

  • Slice types now have a base property that allows public read-only access to their base collections. (SE-0093)

  • File literals in playgrounds have the URL struct type rather than NSURL. (26561852)

  • The functions sizeof(), strideof(), and alignof() have been removed. Instead, these memory layout properties for a type T are now specified as MemoryLayout<T>.size, MemoryLayout<T>.stride, and MemoryLayout<T>.alignment, respectively.

    The functions sizeofValue(), strideofValue(), and alignofValue() have been renamed MemoryLayout.size(ofValue:), MemoryLayout.stride(ofValue:), and MemoryLayout.alignment(ofValue:).

    // Swift 2.3:
    var p = Person()
    sizeofValue(p) // 40
    sizeof(Double.self) // 8
    alignof(Double.self) // 8
     
    // Swift 3.0:
    var p = Person()
    MemoryLayout.size(ofValue: p) // 40
    MemoryLayout<Double>.size // 8
    MemoryLayout<Double>.alignment // 8

    (SE-0136 and SE-0101)

  • The repeating Character and UnicodeScalar forms of String initializers and String.append now must be specified using a repeating String argument. The code previously written as:

      let s1 = String(repeating: "x" as Character, count: 10)
      let s2 = String(repeating: "y" as UnicodeScalar, count: 10)

    is now simplified to:

    let s1 = String(repeating: "x", count: 10)
    let s2 = String(repeating: "y", count: 10)

    The code previously written as:

    s1.append("x" as UnicodeScalar)

    is now simplified to:

    s1.append("x")

    or can also be written as:

    s1.append(String(UnicodeScalar("x")))

    (SE-0130)

  • The functions isUniquelyReferenced() and isUniquelyReferencedNonObjC() have been removed. The function isKnownUniquelyReferenced() should be called instead. The class NonObjectiveCBase which classes using isUniquelyReferenced() needed to inherit from was removed.

    The method ManagedBufferPointer.holdsUniqueReference was renamed to ManagedBufferPointer.isUniqueReference.

    The code previously written as:

    class SwiftKlazz : NonObjectiveCBase {}
    expectTrue(isUniquelyReferenced(SwiftKlazz()))
     
    var managedPtr : ManagedBufferPointer = ...
    if !managedPtr.holdsUniqueReference() {
      print("not unique")
    }

    should now be written as:

    class SwiftKlazz {}
    expectTrue(isKnownUniquelyReferenced(SwiftKlazz()))
     
    var managedPtr : ManagedBufferPointer = ...
    if !managedPtr.isUniqueReference() {
      print("not unique")
    }

    (SE-0125)

  • An Unsafe[Mutable]RawPointer type has been introduced. It replaces Unsafe[Mutable]Pointer<Void>. Conversion from UnsafePointer<T> to UnsafePointer<U> has been disallowed. Unsafe[Mutable]RawPointer provides an API for untyped memory access, and an API for binding memory to a type. Binding memory allows for safe conversion between pointer types. See bindMemory(to:capacity:), assumingMemoryBound(to:), and withMemoryRebound(to:capacity:). (SE-0107)

  • Some UnicodeScalar initializers (ones that are non-failable) changed from non-failable to failable. That is, in case a UnicodeScalar can't be constructed, nil is returned.

    The code previously written as:

    var string = ""
    let codepoint: UInt32 = 55357 // this is invalid
    let ucode = UnicodeScalar(codepoint) // Program crashes at this point.
    string.append(ucode)

    should now be written as:

    var string = ""
    let codepoint: UInt32 = 55357 // this is invalid
    if let ucode = UnicodeScalar(codepoint) {
      string.append(ucode)
    } else {
      // do something else
    }

    (SE-0128)

  • The withUnsafePointer and withUnsafeMutablePointer functions now include a to: argument label. Code using those functions need to add that label.

    The withUnsafePointers and withUnsafeMutablePointers functions (with multiple pointer arguments) have been removed. Replace uses of these functions with nested calls to the single-pointer functions. (See the proposal for an example.)

    The unsafeAddressOf function has been removed. Code using that should be updated to use ObjectIdentifier(x).unsafeAddress.

    The class ManagedProtoBuffer has been removed. References to that class as an explicit type should be renamed to ManagedBuffer. (SE-0127)

  • The standard library provides a new type AnyHashable for use in heterogenous hashed collections. Untyped NSDictionary and NSSet APIs from Objective-C now import as [AnyHashable: Any] and Set<AnyHashable>. (SE-0131)

  • Int.init(ObjectIdentifier) and UInt.init(ObjectIdentifier) were changed to require a bitPattern: label. The initializers on Int and UInt accepting an ObjectIdentifier now need to be specified with an explicit bitPattern: label. For example:

    let x: ObjectIdentifier = ...

    was previously written as:

    let u = UInt(x)
    let i = Int(x)

    but should now be written as:

    let u = UInt(bitPattern: x)
    let i = Int(bitPattern: x)

    (SE-0124)

  • The Boolean protocol has been removed. (SE-0109)

  • The following two methods were added to FloatingPoint:

    func rounded(_ rule: FloatingPointRoundingRule) -> Self
    mutating func round( _ rule: FloatingPointRoundingRule)

    These methods bind the IEEE 754 roundToIntegral operations. They provide the functionality of the C / C++ round(), ceil(), floor(), and trunc() functions and other rounding operations as well.

    As a follow-on to the work of SE-0113 and SE-0067, the following mathematical operations in the Darwin.C and glibc modules now operate on any type conforming to FloatingPoint: fabs, sqrt, fma, remainder, fmod, ceil, floor, round, and trunc. (SE-0113)

  • Operators can now be defined within types or extensions thereof. For example:

    struct Resolved Issues: Equatable {
      let value: Int
     
      static func ==(lhs: Resolved Issues, rhs: Resolved Issues) -> Bool {
        return lhs.value == rhs.value
      }
    }

    Such operators must be declared as static (or, within a class, class final), and have the same signature as their global counterparts. As part of this change, operator requirements declared in protocols must also be explicitly declared static:

    protocol Equatable {
      static func ==(lhs: Self, rhs: Self) -> Bool
    }

    Note that the type checker performance optimization described by SE-0091 is not yet implemented. (SE-0091)

  • The partition method was revised. The collection methods partition() and partition(isOrderedBefore:) have been removed from Swift. They were replaced by the method partition(by:) which takes an unary predicate.

    The code previously written as:

    let p = c.partition()

    should now be written as:

    let p = c.first.flatMap({ first in
      c.partition(by: { $0 >= first })
    }) ?? c.startIndex

    (SE-0120)

  • The functions sizeof(), strideof(), and alignof() have been removed. Instead, these memory layout properties for a type T are now specified as MemoryLayout<T>.size, MemoryLayout<T>.stride, and MemoryLayout<T>.alignment, respectively.

    The functions sizeofValue(), strideofValue(), and alignofValue() have been renamed MemoryLayout.size(ofValue:), MemoryLayout.stride(ofValue:), and MemoryLayout.alignment(ofValue:).

    // Swift 2.3:
    var p = Person()
    sizeofValue(p) // 40
    sizeof(Double.self) // 8
    alignof(Double.self) // 8
     
    // Swift 3.0:
    var p = Person()
    MemoryLayout.size(ofValue: p) // 40
    MemoryLayout<Double>.size // 8
    MemoryLayout<Double>.alignment // 8

    (SE-0136 and SE-0101)

  • The Sequence.flatten() and Collection.flatten() methods were renamed to Sequence.joined() and Collection.joined(). For example in Swift 2.3, this can be written as:

    [[1,2],[3]].flatten()

    In Swift 3.0, this should now be written as:

    [[1,2],[3]].joined() // [1,2,3]
    [[1,2],[3]].joined(separator: []) // [1,2,3]
    [[1,2],[3]].joined(separator: [0]) // [1,2,0,3]

    (SE-0133)

  • Active Compilation Conditions is a new build setting for passing conditional compilation flags to the Swift compiler. Each element of the value of this setting passes to swiftc prefixed with -D, in the same way that elements of Preprocessor Macros pass to clang with the same prefix. (22457329)

  • Two new build settings have been added to enable Swift compiler options:

    • -suppress-warnings (SWIFT_SUPPRESS_WARNINGS)

    • -warnings-as-errors (SWIFT_TREAT_WARNINGS_AS_ERRORS)

    These settings are independent of the build settings for the corresponding clang options. (24213154)

  • The new build setting ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES replaces the EMBEDDED_CONTENT_CONTAINS_SWIFT setting, which has been deprecated. This new setting indicates that Xcode should always embed Swift standard libraries in a target for which it has been set, whether or not the target contains Swift code. A typical scenario for using this setting is when a target directly uses or embeds another product that contains Swift code. (26158130)

  • The removal of implicit bridging conversions (SE-0072) means that empty literal arrays and dictionaries no longer implicitly type-check as NSArray or NSDictionary. This behavior was often unintentional; however, when desired, it can be made explicit using [] as NSArray or [:] as NSDictionary. (20119003)

Resolved Issues

  • An issue where macros within the OpenGL.GL3 module were not visible in Swift has been resolved. (26731529)

  • Protocol type values should no longer have ordering issues in generated Objective-C headers. (27746149)

  • Inside an extension of an Objective-C lightweight generic class, the Swift compiler will no longer print an error stating that uses of an initializer for another generic Objective-C class "access the class's generic parameters." (27796375)

  • Dictionary and Set literals with AnyHashable keys no longer require manual wrapping.

    func doSomething(userInfo: [AnyHashable: Any])
     
    // This now works
    doSomething(userInfo: ["foo": "Foo", "bar": "Bar"])

    (27615802)

  • In Xcode 8 beta 6, archiving a Bool value converted to NSNumber would produce an integer rather than a Boolean value. This has been fixed. (27897683)

  • When previous betas of Swift 3 imported option sets, option names with the value 0 were suppressed because they are synonymous with the empty option set, []. In cases where the names of these constants are significant, those zero-valued constants are now available. For example, when setting the title for the normal state, instead of writing:

    button.setTitle("OK", for: [])

    You can now write the clearer alternative:

    button.setTitle("OK", for: .normal)

    (26485596)

  • Comments are now treated as whitespace when determining whether an operator is prefix, postfix, or binary. For example:

    if /*comment*/!foo { ... }
    1 +/*comment*/2

    This also means that comments can no longer appear between a unary operator and its argument.

    foo/* comment */! // no longer works

    Any parse errors resulting from this change can be resolved by moving the comment outside of the expression. (SE-0037)

Known Issues

  • When using static in an extension of an Objective-C class, the compiler may produce the error "a declaration cannot be both 'final' and 'dynamic'". This error is a consequence of Swift using dynamic to implement members exposed to Objective-C in extensions, and static being equivalent to class final when used within a class or extension of a class. In some cases, this error will not have correct location information.

    As a workaround, use class instead of static (making the method or property non-final) or add @nonobjc (making the method or property non-dynamic and hiding it from Objective-C). (20512544)

  • Objective-C lightweight generic classes are now imported as generic types in Swift. Because Objective-C generics are not represented at runtime, there are some limitations on what can be done with them in Swift:

    • If an ObjC generic class is used in a checked as?, as!, or is cast, the generic parameters are not checked at runtime. The cast succeeds if the operand is an instance of the ObjC class, regardless of parameters.

      let x = NSFoo<NSNumber>(value: NSNumber(integer: 0))
      let y: AnyObject = x
      let z = y as! NSFoo<NSString> // Succeeds
    • Swift subclasses can only inherit an ObjC generic class if its generic parameters are fully specified.

       // Error: Can't inherit ObjC generic class with unbound parameter T
      class SwiftFoo1<T>: NSFoo<T> {}
       
      // OK: Can inherit ObjC generic class with specific parameters
      class SwiftFoo2<T>: NSFoo<NSString> {}
    • Swift can extend ObjC generic classes, but the extensions cannot be constrained, and definitions inside the extension do not have access to the class's generic parameters.

      extension NSFoo {
        // Error: Can't access generic param T
        func foo() -> T {
          return T()
        }
      }
       
      // Error: extension can't be constrained
      extension NSFoo where T: NSString {
      }
    • Foundation container classes NS[Mutable]Array, NS[Mutable]Set, and NS[Mutable]Dictionary are still imported as nongeneric classes for the time being. (SE-0057)

  • The Swift compiler does not check access correctly for overrides and for members that satisfy protocol requirements. This can lead to spurious diagnostics and even compiler crashes, and can also lead to certain incorrect code being left undiagnosed. This will be fixed in a future version of Swift 3, which may lead to new diagnostics on existing Swift 3 code.

    To work around this issue in the current release, use private for top-level classes instead of fileprivate. To avoid issues in later releases, always make overrides and members that satisfy protocol requirements at least as accessible as their enclosing type, or as accessible as the method being overridden or the requirement being satisfied. (In particular, such members should never be marked private.) (27820665)

  • If a target containing Swift code depends on Objective-C headers (including in frameworks), and those headers have been changed since the product was built, the LLDB server may fail to load debug info properly for that target. As a workaround, avoid using Run Without Building when headers are out of date. (26845120)

  • If a private or fileprivate method is declared in an extension of an Objective-C lightweight generic class, the Swift compiler will incorrectly report that a call to that method "accesses the class's generic parameters." For example:

    extension GenericObjCClass {
      private func foo() {}
      func bar() { foo() }
    }

    As a workaround, avoid declaring methods as private in Objective-C lightweight generic class extensions. (27796182)

  • Dynamically casting an NSArray to [Any] using as!, as?, or is may fail at runtime with an error message "array element type is not bridged to Objective-C". As a workaround, try casting to [AnyObject] instead. (28033520)

  • The compiler will crash if an imported Objective-C lightweight generic class is made to conform to a Swift protocol with an associated type bound to one of the class's generic parameters. For example:

    // Objective-C
    @interface Foo<Bar>: NSObject
    @end
     
    // Swift
    protocol Runcible {
      associatedtype Spoon
      var spoon: Spoon { get }
    }
     
    extension Foo: Runcible {
      // Bar is the generic parameter to Foo.
      // Binding it to an associated type causes a crash.
      typealias Spoon = Bar
      var getSpoon: Bar { return Bar() }
    }

    To work around this issue, try expressing the protocol conformance with the associated type as AnyObject, or whatever protocol the generic parameter is constrained to. For example, the above extension could be rewritten as:

    extension Foo: Runcible {
      // Use AnyObject instead of Bar as the associated type.
      typealias Spoon = AnyObject
      var getSpoon: AnyObject { return Bar() }
    }

    (26602097)

  • Throwing methods that are marked @objc and return a type that is not bridgeable to Objective-C will crash the compiler. To work around this issue, explicit mark the function @nonobjc. For example:

    protocol Widget {
      func getPartCount() throws -> UInt32
    }
     
    class SimpleWidget : NSObject, Widget {
      @nonobjc func getPartCount() throws -> UInt32 {
        return 1
      }
    }

    (28035614)

  • Using a typealias defined in Swift as the argument type for a generic Objective-C class can result in a compiler crash. As a workaround, use the underlying type instead. (27867166)

  • Operator methods in classes such as == and + must be marked with @nonobjc. (27926415)

  • Casting values of CF collection types (for example, CFArray) directly to their bridged Swift equivalents (for example, [String]) may fail unexpectedly. As a workaround, adding an intermediate cast to AnyObject or Any may allow the cast to succeed. (25986247) 

  • The Swift compiler may segfault or crash on an assertion failure if a subclass overrides a method that returns an optional struct, enum, or tuple type of its base class to give it a nonoptional return. For example:

    struct X {}
     
    class Foo {
      func foo() -> X? { return nil }
    }
    class Bar: Foo {
      override func foo() -> X { return X() }
    }
    class Bas: Bar {
      override func foo() -> X { return X() }
    }
     
    let x = Bar().foo() // Causes compiler to crash

    As a workaround, the non-optional form can be declared as a new method:

    class Bar: Foo {
      override func foo() -> X? { return nonOptionalFoo() }
      func nonOptionalFoo() -> X {
        return X()
      }
    }

    (23472654)

  • The code catch ... as AnyObject may get miscompiled, failing to catch errors that can be converted to AnyObject.

    As a workaround, move the AnyObject coercion into the code block:

    // Workaround
    do {
      try something()
    } catch let error {
      let errorObject = error as AnyObject
      ...
    }

    (27581060)

  • Using a string, array, or dictionary literal in a context where a class type is expected will give an incorrect error message and fixit suggestion. For example, the following code will generate a suggestion to write string as! NSCopying, which will not work.

    func foo(_ x: NSCopying) {}
    foo("string")

    The correct fix is to write: as NSString. (27668917)

  • The Today extension template has an incorrect protocol method signature when using Swift. If you create a Today extension for macOS or iOS, you'll receive a warning when compiling. This warning states that one of the methods that's meant to satisfy an optional NCWidgetProviding protocol method does not match the protocol method's signature and will not be called. To work around this issue, replace this code:

    func widgetPerformUpdate(completionHandler: ((NCUpdateResult) -> Void)) {

    with this code:

    func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {

Toolchains

New Features

  • Xcode 8 supports switching toolchains (such as those from swift.org), including for Playgrounds execution, without relaunching Xcode. (23135507, 26200406, 27593280, 23287417, 26704661)

Xcode Server

New Features

  • Xcode Server includes improvements to issue tracking and blame, including more accurate author identification, the ability to track bot configuration changes over time, and the ability to attribute new issues to those changes. (22814617)

  • You can configure whether upgrade integrations will run when your server is upgraded. (27135245)