Swiftで関数ポインタっぽい処理

Swift言語で関数ポインタぽい処理ができるのか試してみました。

関数ポインタとはC/C++などでよくつかう下記のようなヤツです。

typedef void (*TNotifyEvent)(System::TObject *Sender);

これはC++で書いたものですがこれを使う場合

void hoge(TObject *Sender){
}
void foo(TObject *Sender){
 TNotifyEvent event1 = &hoge;
 event1(Sender);
}

event1をコールするとhoge()関数が実行されます。
ここまではC++の例です。

Swiftの場合

Xcode11.5 Swift5.1で 同じような処理を行う場合下記のように書きました。

typealias TNotifyEvent = (_ sender: Any) -> Void

class THoge{
 var event1: TNotifyEvent!
 func f1(_ i: Int){
  event1(i as Any)
 }
}

class TFoo{
 var hoge1: THoge
 init() {
  hoge1 = THoge()
  hoge1.event1 = act1
 }
 func act1(_ sender: Any){
  let i:Int = sender as? Int ?? 0
  print(“Action “ + String(i))
 }
}

上記のように記述することができます。

let foo1 = TFoo()
foo1.hoge1.f1(100)

TFooの中のTHoge.f1()というファンクションを実行してTFoo.act1()が実行されます。


下記のコードは、先程作成したTNotifyEventAnyではなくジェネリックスで試してみました。

typealias TNotifyEvent<T> = (_ sender: T) -> Void

class THoge{
 var event1: TNotifyEvent<Int>!
 func f1(_ i: Int){
  event1(i)
 }
}

THogeクラス内のTNotifyEventTNotifyEvent<Int>として利用できます。
このことによってAnyへのキャストの必要もなくなりコードがシンプルに実装できます。

Swift CocoaPods could not find対処方法

pod installを実行して CocoaPods could not find compatible versions for pod “Firebase/Analytics”が出た場合の対処方法

Analyzing dependencies
Adding spec repo trunk with CDN https://cdn.cocoapods.org/
[!] CocoaPods could not find compatible versions for pod “Firebase/Analytics”:
  In snapshot (Podfile.lock):
    Firebase/Analytics (= 6.7.0)
 
  In Podfile:
    Firebase/Analytics
 
None of your spec sources contain a spec satisfying the dependencies: Firebase/Analytics, Firebase/Analytics (= 6.7.0).
 
You have either:
 * out-of-date source repos which you can update with pod repo update or with pod install --repo-update.
 * mistyped the name or version.
 * not added the source repo that hosts the Podspec to your Podfile.

リポジトリが「out-of-date」古いから更新しろと書いているので下記を実行する

pod repo update
pod install –repo-update

再度下記を実行する

pod deintegrate
pod install

2022 MJELD TECHNOLOGIES. ALL RIGHTS RESERVED