[Swift] Crash when constructing an NSString by calling init() on a downcasted instance of AnyClass

Originator:AustinZheng
Number:rdar://19831709 Date Originated:February 13, 2015
Status:Closed Resolved:
Product:Developer Tools Product Version:
Classification: Reproducible:Always
 
Summary:
The 'dynamicType' special keyword/property can be used to retrieve the runtime type of an object (as an AnyClass). The type can then be downcast using as? to produce a T.Type object, on which initializers and class methods can be called.

It's possible to construct a simple program which perform the above operation on an NSString, and then attempts to initialize a new NSString, and successfully compile this program. However, this program crashes when run because it cannot find the proper initializer to use.

Steps to Reproduce:
Run the sample project enclosed.

Expected Results:
Xcode produces an error when trying to compile the program, or program successfully compiles and runs and is able to use stringTypeValue() to instantiate a new NSString instance.

Actual Results:
Application crashes when trying to instantiate a new NSString instance (line 22), with the error message in the console: "/SourceCache/swiftlang/swiftlang-602.0.37.3/src/swift/stdlib/core/StringBridge.swift: 128: 20: fatal error: use of unimplemented initializer 'init()' for class 'Swift._NSContiguousString'"

Version:
Both Xcode 6.1 and 6.2 beta (6D520o), running on OS X Yosemite (10.10.2).

Notes:
I don't think this is isolated to NSStrings; I think it may be an issue for all Foundation bridged classes that are implemented using Objective-C class clusters.

Configuration:


Attachments:
'SwiftMetaclass.zip' was successfully uploaded.

Note: SwiftMetaclass's single source file is reproduced below in its entirety:

import Foundation

println("Hello, World!")

func classForObject(object: AnyObject) -> AnyClass {
    return object.dynamicType
}

let anyTypeValue : AnyClass = classForObject("hello world")

if let stringTypeValue = anyTypeValue as? NSString.Type {
    println("classForObject returned a NSString.Type")
    // Crashes here
    let newString = stringTypeValue()
}

Comments

Closed with the comment "There are no plans to address this.".

By AustinZheng at Feb. 27, 2015, 11:33 p.m. (reply...)

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!