1

Swift 1.2 / Xcode 6.3.

Why is this valid:

class RangeDelegateNongeneric: NSObject, UIPickerViewDataSource {
    var values = [Int]()

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return values.count
    }
}

but this isn't:

class RangeDelegateGeneric<T>: NSObject, UIPickerViewDataSource {
    var values = [T]()

    func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return values.count
    }
}

Error: Type RangeDelegateGeneric<T> does not conform to protocol UIPickerViewDataSource

Even more oddly, the Fix-it message: Candidate is not @objc, but protocol requires it prepends @objc to the beginning of each function, but that doesn't Fix-it, and the Fix-it tool is happy to repeatedly prepend @objc!

BaseZen
  • 8,650
  • 3
  • 35
  • 47
  • On which line you get this error? I copied the generic class into my playground and it seems to compile fine. – Abdullah Apr 12 '15 at 07:36
  • 1
    Generic classes *cannot* be delegates for Foundation methods, see for example this answer: http://stackoverflow.com/a/26104946/1187415. – Martin R Apr 12 '15 at 07:42
  • Thanks. In practice this gives me what I need to know. While the compiler's error message is clear proof, if you can point to where in the Apple Tech Docs this is explained, I am happy to credit you with an answer. I was frustrated in that I couldn't find this fact clearly stated in any spec. – BaseZen Apr 12 '15 at 18:29

1 Answers1

1

This is fixed in Swift 2.0, specifically tested in Xcode 7 (beta 5 as of this writing).

99% sure this blog fragment explains it, although a more compiler-nerd-friendly explicit spec statement is bizarrely difficult to find:

https://developer.apple.com/swift/blog/?id=29

[Emphasis mine]

Swift-er SDKs: Swift 2 works even better with the Apple SDKs, thanks in part to two new features in Objective-C: nullability annotations and generics. The SDKs have been updated to annotate API that cannot return nil so you don’t need to use optionals as often. And with a true generics system employed by the SDKs you can more often preserve detailed type information in your Swift 2 code.

BaseZen
  • 8,650
  • 3
  • 35
  • 47