NSArray <=> Swift array bridging leaking memory

Originator:michael
Number:rdar://27909014 Date Originated:18-Aug-2016
Status:Open Resolved:
Product:Developer Tools Product Version:
Classification:Performance Reproducible:Always
 
Summary:
Bridging an NSArray from Objective-C to a typed array in Swift can cause memory leaks to be reported in Instruments. Changing the code from a typed array to an NSArray fixes the leak, but only when each member in the array is cast individually:

```
array.map { $0 as? ElementType}.filter { $0 != nil }.flatMap { $0 }
```

Happens when either -O (fast) or -O -whole-module-optimization compiler flags are enabled.

Steps to Reproduce:
1. Download the attached project zip and unzip.
2. Open in Xcode and select a simulator or device.
3. Profile the app in Instruments, selecting the 'Leaks' instrument if prompted (either Simulator or Device).
4. Change `#if 1` to `#if 0` on line 15 in `AppDelegate.m`.
5. Profile the app again.

Expected Results:
There shouldn’t be any memory leaks, regardless of whether typed bridging is used.

Actual Results:
Instruments detects a memory leak when bridging to typed array from Objective-C. (see attached screenshot)

Version:
Xcode Version 7.3.1 (7D1014)
OS X 10.11.6

Notes:


Configuration:
Apple Swift version 2.2 (swiftlang-703.0.18.8 clang-703.0.31)
Target: x86_64-apple-macosx10.9

SwiftArrayBridgingLeakExample.zip - configuration file has been successfully uploaded.

Attachments:
'Screenshot 2016-08-18 11.14.40.png' and 'SwiftArrayBridgingLeakExample.zip' were successfully uploaded.

Comments


Please note: Reports posted here will not necessarily be seen by Apple. All problems should be submitted at bugreport.apple.com before they are posted here. Please only post information for Radars that you have filed yourself, and please do not include Apple confidential information in your posts. Thank you!