Objective-C 宏是這樣的:
#define CALL_FUNC(classname, times, classfuncWithParamter) \
{\
for (int i = 0; i< times; i++) {\
[classname classfuncWithParamter]\
}\
}\
調用 Objective-C:
CALL_FUNC(AnClass, 10, setName:@"test" withPhone:12345)
令我困惑的是這個 for 循環調用函數,宏可以做文本替換來做到這一點
在 Swift 中處理這個宏的最佳方法是什麼?
正如人們在評論中所說,您需要使用泛型和閉包。訣竅是,如果要支持多個參數,則必須多次聲明“宏”:
// 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...
對於您問題中的示例,調用將如下所示:
call(times: 10, AnClass.setName(_:withPhone:), "test", 12345)
,或者你可以傳遞一個閉包,並使代碼更具可讀性,如下所示:
call(times: 10) { AnClass.setName("test", withPhone: 12345) }
,如果你選擇這條路,你只能保留第一個call
定義,沒有參數的那個:func call<T>(_ times: Int, f: () -> T)
。在閉包中調用所需的函數也更加靈活,因為您可以在該閉包中支持任意數量的參數。
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다