Swift 4.0中存储OC自定义模型至id属性后无法识别类型的问题
Hey there, let's break down why your type check isn't working and get it sorted out quickly!
The Root Cause
Your Objective-C DetailsModel has a property declared as id model — in Swift, this gets bridged to Any? (an optional Any type). When you run type(of: current.model), you're actually checking the type of the optional wrapper itself (Optional<Any>.Type), not the underlying CarModel instance inside it. That's why your comparison to type(of: CarModel()) (which is CarModel.Type) fails, and the console shows Optional<Any>.
Solutions to Try
Here are three solid approaches, ordered by recommendation:
1. Use Safe Type Casting (Recommended)
This is the most Swift-idiomatic way to handle this scenario. Instead of checking types directly, try casting the value to CarModel — if it succeeds, you get a non-optional instance to work with:
if let carModel = current.model as? CarModel { // Do your work with carModel here, it's guaranteed to be a CarModel instance print("Successfully recognized CarModel!") } else { // Handle cases where the model isn't a CarModel }
This method is safe, concise, and avoids dealing with optional wrapper types directly.
2. Explicitly Unwrap and Check Type
If you really need to use type(of:), first unwrap the optional current.model to get the underlying value, then compare against the type itself (using CarModel.self instead of creating a new instance):
// First make sure the model isn't nil if let unwrappedModel = current.model { if type(of: unwrappedModel) == CarModel.self { // Type matches, proceed with your logic } }
Note: Using CarModel.self is more efficient than type(of: CarModel()) because you don't create an unnecessary instance of CarModel.
3. Refine the Objective-C Model (If Possible)
If DetailsModel's model property only ever holds CarModel instances, you can update the Objective-C declaration to be more specific:
@interface DetailsModel : NSObject @property (nonatomic, strong) CarModel *model; @end
In Swift, this property will now bridge to CarModel?, making type checks or casts completely straightforward. If you need to store multiple types though, stick with the first solution.
Wrap-Up
The first approach (safe type casting) is almost always the best choice for Swift code — it keeps your logic clean and avoids potential crashes from forced unwrapping.
内容的提问来源于stack exchange,提问作者Paras Gorasiya




