Swift: is and as operators should accept runtime type arguments
| Originator: | vic.gbsmith | ||
| Number: | rdar://18895280 | Date Originated: | 06-Nov-2014 05:40 PM |
| Status: | Open | Resolved: | |
| Product: | Developer Tools | Product Version: | Xcode 6.1 (6A1052d) |
| Classification: | Enhancement | Reproducible: | Always |
Summary:
Swift provides the ‘is’ and ‘as’ operators to select behaviour based on the type of an object received at runtime. However, the type selected on itself can only be specified statically at compile time. For example, we might want an extension on UIView helps with loading from a nib. The code might be:
extension UIView {
class func loadFromNib(name: String) -> Self? {
var items = UINib(nibName: name, bundle:nil).instantiateWithOwner(self, options: nil)
for obj in items {
if obj is Self {return obj}
}
return nil
}
}
This is not currently possible with the Swift operators. It is possible with the isKindOfClass() function, but this is not applicable to all types. This also requires returning type UIView specifically, like this:
extension UIView {
class func loadFromNib(name: String) -> UIView? {
var items = UINib(nibName: name, bundle:nil).instantiateWithOwner(self, options: nil)
for obj in items {
if obj.isKindOfClass(self) {return obj as? UIView}
}
return nil
}
}
Steps to Reproduce:
Use the ‘is’ or ‘as’ operator to check for a type known dynamically
Expected Results:
Code compiles, runtime type comparison is made.
Actual Results:
Compilation error.
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!