Skip to content

Instantly share code, notes, and snippets.

@dodikk
Last active October 4, 2018 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dodikk/16d4e7b4ef6cb0cf98cd2dac44e13003 to your computer and use it in GitHub Desktop.
Save dodikk/16d4e7b4ef6cb0cf98cd2dac44e13003 to your computer and use it in GitHub Desktop.

Reasoning behind the macro

#define KINDOF_CAST(arg) ((__kindof typeof(arg))(arg))

UICollectionViewFlowLayout* flowLayout = KINDOF_CAST(self.collectionView.collectionViewLayout);

The macro works at compile time. It relies on the collectionViewLayout property declaration type. So the expression results in

UICollectionViewFlowLayout* flowLayout = (__kindof UICollectionViewLayout)(self.collectionView.collectionViewLayout);

The __kindof UICollectionViewLayout type silences the compiler's "type mismatch" warnings because UICollectionViewFlowLayout is a child of UICollectionViewLayout.

The templates above do the runtime checks so these casts might co-exist depending on the "safety" level chosen by the programmer.

#define KINDOF_CAST(arg) ((__kindof typeof(arg))(arg))
// By Scherbinin Anatoly from the cocoa chat ("Какао-чат: Cocoa, Xcode, objective C")
UICollectionViewFlowLayout* flowLayout = KINDOF_CAST(self.collectionView.collectionViewLayout);
@dodikk
Copy link
Author

dodikk commented Oct 4, 2018

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment