0
class SuperDelegate <T: AnyObject> {

  func addDelegate(delegate: T)
  {

  }
}

My question is about T key, does it mean the same as id in Objective-c? I mean about case of uses.

how to understand the first line class SuperDelegate <T: AnyObject> Sorry I am new in Swift.

As Objective C program for me this line means that we make class to conform a protocol that has to implement all required method. But I don't understand func addDelegate(delegate: T) is this the same like

- (void)addDelegate:(id)delegate which is a property id <T> delegate.

Matrosov Oleksandr
  • 25,505
  • 44
  • 151
  • 277
  • Do yourself a favor and read: https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/index.html#//apple_ref/doc/uid/TP40014097-CH3-ID0. – damirstuhec Mar 18 '16 at 12:45

1 Answers1

0

Yes you are correct in your assumptions that AnyObject behaves like id:

You can call any Objective-C method and access any property on an AnyObject value without casting to a more specific class type. This includes Objective-C compatible methods and properties marked with the @objc attribute.

but you have used it here as a generic type rather than as a concrete type that should be cast to. The class is requiring a type that adheres to the AnyObject protocol but it isn't forcing it to be AnyObject (see header files: cmd + click on AnyObject inside Xcode).

So your instance could be instantiated SuperDelegate<AnyObject> but it could also be instantiated SuperDelegate<NSDate>. This means that the whole subset of ObjC methods and properties cannot be guaranteed as they can with a cast to AnyObject as a concrete type because at runtime T might represent NSDate or NSNumber or any other class.

To achieve what you want you would need to write:

class SuperDelegate {
    func addDelegate(delegate: AnyObject)
    {

    }
}

But Swift is a strongly-typed language and it would normally be the case that you had a delegate protocol and that the delegate for your type adhered to the delegate protocol:

protocol DelegateProtocol {
    func somethingHappened()
}
struct MyTypeDelegate:DelegateProtocol {
    func somethingHappened() {
        print("Thanks for telling me!")
    }
}
struct MyType {
    var delegate:DelegateProtocol?
    func tellDelegateSomethingHappened() {
        delegate?.somethingHappened()
    }
}
let del = MyTypeDelegate()
var type = MyType()
type.delegate = del
type.tellDelegateSomethingHappened()
Community
  • 1
  • 1
sketchyTech
  • 5,746
  • 1
  • 33
  • 56