How can I specify the key and value datatype of an NSDictionary argument in swift?

301 views Asked by At

I would like to define a function in swift that can be used in objective-c as well. I have a enum:

    @objc public enum BookType: Int {
      case novel
      case magazine
    
      func name() -> String {
          switch self {
          case .novel:
              return "novel"
          case .magazine:
              return "magazine"
          }
      }
  }

And the function is:

@objc public func uploadBookImages(images: [BookType: UIImage]) {
       // code here
}

This function will bring me an compile error said that:

Method cannot be marked @objc because the type of the parameter cannot be represented in Objective-C

It might because objective-c doesn't accept swift dictionary since it is a structure. I am thinking to use NSDictionary instead of a swift dictionary. However, how can I specify the argument data type to [BookType: UIImage] using a NSDictionary? I want to pass a NSDictionary<BookType: UIImage> to the function when I call it.

1

There are 1 answers

4
Dinesh On

You need to use NSDictionary instead of swift Dictionary

  func uploadBookImages(images: NSDictionary) {
    // code here
    print(images)
}

Usage:

   let dictParams:Dictionary<BookType, Int> = [
        BookType.magazine : 1,
        BookType.novel : 2,
        ];
    
    uploadBookImages(images: dictParams as NSDictionary)