How rewrite Objective-C Macro expand with swift

waitianlou

The Objective-C Macro is like:

#define CALL_FUNC(classname, times, classfuncWithParamter) \ 
{\
     for (int i = 0; i< times; i++) {\
          [classname classfuncWithParamter]\
     }\
}\

calling for Objective-C:

CALL_FUNC(AnClass, 10, setName:@"test" withPhone:12345)

What puzzles me is this for-loop call func, Macro can do text substitution to do this

What is the best way deal with this Macro in Swift?

Cristik

As people have stated in the comments, you'll need to use generics and closures. The trick is that you'll have to declare the "macro" multiple times if you want to support multiple numbers of parameters:

// for functions with no arguments
func call<T>(times: Int, _ f: () -> T) {
    for i in 0..<times {  f() }
}

// for functions with one argument
func call<A, T>(times: Int, _ f: (A) -> T, _ arg: A) {
    for i in 0..<times { f(arg) }
}

// for functions with two arguments
func call<A1, A2, T>(times: Int, f: (A1, A2) -> T, _ a1: A1, _ a2: A2) {
    for i in 0..<times { f(a1, a2) }
}

// for functions with three arguments
func call<A1, A2, A3, T>(times: Int, f: (A1, A2, A3) -> T, _ a1: A1, _ a2: A2, _ a3: A3) {
    for i in 0..<times { f(a1, a2, a3) }
}

// and so on...

For the sample from your question, the call would look something like this:

call(times: 10, AnClass.setName(_:withPhone:), "test", 12345)

, or you can pass a closure, and make the code more readable, like this:

call(times: 10) { AnClass.setName("test", withPhone: 12345) }

, and if you choose this road you can keep only the first call definition, the one without arguments: func call<T>(_ times: Int, f: () -> T). Calling the desired function within a closure is also more flexible, as you can support any numbers of arguments within that closure.

Este artículo se recopila de Internet, indique la fuente cuando se vuelva a imprimir.

En caso de infracción, por favor [email protected] Eliminar

Editado en
0

Déjame decir algunas palabras

0Comentarios
Iniciar sesiónRevisión de participación posterior

Artículos relacionados

How to use Objective-C enum in Swift

How to convert this Swift syntax into Objective-C?

How to call an Objective C class method in Swift

Как я могу отправлять (и получать) чрезвычайно большие плавающие массивы из Swift в Objective c ++ в c ++, а затем выполнять резервное копирование в Swift?

How do I make a C macro expand to a struct and function using this method

Разница между перечислителем и итератором в Swift или Objective C

Увеличивает ли добавление библиотек Objective-C в проект Swift размер приложения?

Как преобразовать строку кода из Objective-C в Swift в массиве сортировки?

Невозможно вызвать некоторые функции Swift из Objective-c (другие работают)

Как вы вызываете вариативный метод Swift из Objective-C?

преобразование objective-c в синтаксис swift: @ ()

Используйте классы Swift в файлах Bridging Objective C

Свойство, определенное в файле Objective C, не отображается в Swift (та же цель)

How to expand NSPopUpButton in Swift programmatically?

How to use a swift module in an objective-c module with SwiftPM?

How to make a Swift String enum available in Objective-C?

How to access a private objective C variable in Swift View Controller?

How can method in Swift with inout parameter be used in Objective-C?

How to use Objective-C framework in Swift without Bridging Header?

How to rewrite an initializer in Swift for a subclass

Ошибка сборки при использовании как библиотеки objective-c, так и библиотеки swift с Cocoapods

iOS Swift to Objective-C как передавать слабые ссылки на массивы?

Объявите строку с типом данных char в файле Objective c .m и используйте ее в Swift

Фреймворк Typhoon: Swift или Objective-C

Как вызвать код Swift из Objective-C в целевой платформе Framework?

Извлечение значения из SwiftDeferredNSDictionary по ключу в Objective C, где ключ - это Swift enum

Можно ли использовать модуль, написанный на Swift, в проекте Objective-C, если классы не имеют префикса `@ objc`?

Вызов функции Objective-C, определенной в файле .h из Swift

How to get value macro in C?

TOP Lista

CalienteEtiquetas

Archivo