Does Objective-C support Generics?

前端 未结 6 600
后悔当初
后悔当初 2020-12-02 00:07

I wonder whether Objective-C offers any support for generics?

For instance, consider a method:

-(void) sort: (NSMutableArray *) deck {
}
6条回答
  •  自闭症患者
    2020-12-02 00:41

    Not directly, no. There a few ways to simulate it, but it requires a lot of wrapper code, boilerplate code, and runtime overhead. I just switch to Objective-C++ and use C++ templates when I want or need proper generics.

    So if you wanted to introduce typesafety/checks to an NSArray, you could approach it using something like this:

    template 
    class t_typed_NSMutableArray {
    public:
        t_typed_NSMutableArray() : d_array([NSMutableArray new]) {}
        ~t_typed_NSMutableArray() { [d_array release]; }
    
        /* ... */
    
        T* operator[](const size_t& idx) {
            T* const obj([this->d_array objectAtIndex:idx]);
            assert([obj isKindOfClass:[T class]]);
            return obj;
        }
    
        void addObject(T* const obj) {
            assert([obj isKindOfClass:[T class]]);
            [this->d_array addObject:obj];
        }
    
    private:
        NSMutableArray * const d_array;
    };
    

    in use:

     t_typed_NSMutableArray array([self cards]); // < note this exact constructor is not defined
    
     Card * firstCard = array[0]; // << ok
     NSString * string = array[0]; // << warning
    

    then you also get type safety and overloading when passing the collection, so you could not pass t_typed_NSArray as an t_typed_NSArray.

提交回复
热议问题