简体   繁体   中英

String does not conform to type AnyObject in NSarray Swift

I am creating a custom object in swift. One of the properties of that object is an array, meant to contain strings:

Exersice (name: "Test", type: "Test", muscles: NSArray(objects: "muscle1", "muscle2"), descriptionString: "Test", pace: true, sets: 1, reps: NSMutableArray(15, 12, 12), time: false, duration: 0)

This is the part the question is about:

muscles: NSArray(objects: "muscle1", "muscle2")

I keep on getting an error:

String does not conform to type AnyObject

I just don't understand why. Looking around on the web shows many cases of this error, but none in this context or helpful in solving this problem.

How do I get rid of this error? Any help would be highly appreciated

NSArray can only hold reference types, whereas Swift's String is a value type. String instances are normally automatically bridged to NSString , but the constructor you're using for the NSArray explicitly expects AnyObject , so that kind of bridging is defeated. You should be able to use a Swift Array instead:

Exersice (name: "Test", type: "Test", muscles: ["muscle1", "muscle2"], ...

The problem here is not NSArray(objects: "muscle1", "muscle2") , but this:

NSMutableArray(15, 12, 12)

This should be

NSMutableArray(objects: 15, 12, 12)

But, as @NateCook said in his answer, you should use Swift Array .

If your Exersice class expects a String array anyway, then make sure the initializer declares it takes a string array

init(name: String, type: String, muscles: [String]) {}

Then Nate's answer above is sufficient.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM