Nirmal
Nirmal

Reputation: 5

‘AnyHashable’ is not convertible to ‘NSObject’

I am converting mine Objective-C code to Swift. I am having my own DataStructure class called “DCclass" inherrited from "NSObject"... i have done all required things like: In Bridging-header imported the “DCclass.h" and etc things fine but while having its for in loop i am facing error something like its type conversion issue. Thanks In Advance.

Current Objective-C code:

#import “DCclass.h”
@interface LPFPickerCell ()
@property (nonatomic) NSMutableArray *myMutableArray;
@end

@implementation LPFPickerCell
- (void)setSelectedData:(NSString *) selectedString
{    
    int i = 0;
    for (DCclass *dc in self.myMutableArray)    /// Swift is showing compile time error here
    {
        NSLog(@"DCclass.empName = %@",dc.empName);
    }
}
@end

Converted Swift Code:

class LPFPickerCell {

    var myMutableArray = [AnyHashable]()

    func setSelectedData(_ selectedString: String?) {
        let i: Int = 0
        for dc: DCclass in myMutableArray {    ///‘AnyHashable’ is not convertible to ‘DCclass’
        print("DCclass.empName = \(dc.empName)")
        }
    }
}

Upvotes: 0

Views: 647

Answers (2)

Ankit Jayaswal
Ankit Jayaswal

Reputation: 5679

The AnyHashable type forwards equality comparisons and hashing operations to an underlying hashable value, hiding its specific underlying type.

You can store mixed-type keys in dictionaries and other collections that require Hashable conformance by wrapping mixed-type keys in AnyHashable instances:

Problem is that using AnyHashable will not work for type DCclass and so you need to manually cast the myMutableArray to particular type:

var myMutableArray = [DCclass]()

Convert code would be like:

class LPFPickerCell {
    var myMutableArray = [DCclass]()
  
    func setSelectedData(_ selectedString: String?) {
        let i: Int = 0
        for dc: DCclass in myMutableArray {  
            print("DCclass.empName = \(dc.empName)")
        }
    }
}

Upvotes: 1

DionizB
DionizB

Reputation: 1507

Maybe you need to change your array type

var myMutableArray = [AnyHashable]()

to

var myMutableArray = [DCclass]()

And then in the for loop you can access it like this

for dc in myMutableArray {    
    print("DCclass.empName = \(dc.empName)")
}

Upvotes: 3

Related Questions