chakrit chakrit - 5 months ago 7
Swift Question

Swift: How to declare a property with classes' names

For example, this snippet is taken from

definition in Swift:

// Access the underlying CGColor or CIColor.
public var CGColor: CGColor { get }

However attempting to do the same for, let's say
, in my own class causes an error:

public class MyClass {
public var NSError: NSError {
return NSError(domain: "mydomain", code: 0, userInfo: [:])

line shows
Use of undeclared type 'NSError'

Is this still possible? What's a good way to do this?

Apple Swift version 2.2 (swiftlang-703.0.18.1 clang-703.0.29)

Target: x86_64-apple-macosx10.9


You could do this by creating a typealias for NSError, NSErrorRef. You would then refer to this typealias throughout your class, as NSError would now refer to a property, not a class.

public typealias NSErrorRef = NSError

public class MyClass {
    public var NSError:NSErrorRef {
        return NSErrorRef(domain: "", code: 0, userInfo: nil)

However, I would never recommend this.

I suspect the only reason that CGColor is named that way in the Swift header of UIColor is simply to preserve interoperability with Objective-C. As for why it works without any confusing errors – I can't say. Although, if you actually look in the docs of UIColor, you'll see CGColor is actually listed as cgColor (when Swift is selected) – which shows even Apple thinks it isn't defined correctly!

In any case, convention states that properties should start with a lowercase letter (in order to prevent this kind of confusion in the first place). So you could do this instead:

public class MyClass {
    public var nsError:NSError {
        return NSError(domain: "", code: 0, userInfo: nil)

Or even better, you could just name your property error – as prefixes should be seldom used in Swift anyway (unless you need to disambiguate – which you actually appear to need to do in your case).

public class MyClass {
    public var error:NSError {
        return NSError(domain: "", code: 0, userInfo: nil)