LoginSignup
2
2

More than 5 years have passed since last update.

ObjCとSwift3が混在するプロジェクトでメソッド名にWith~がついてObjC側からSwiftのメソッドが見られない時の対策

Posted at

Xcode8でBuildが通らなくなる。

環境

  • macOS Sieera 10.12
  • Xcode8 8A218a
  • Swift3.0
  • ObjCのプロジェクトにSwiftのコードを混ぜ込んだプロジェクト
    • bridgeヘッダー等を作ってやるやつ

現象

  • application-Swift.h 等でSwift側のメソッドをObjCに共有しているところで、メソッド名が勝手にWith~とつく
  • ObjC側で、Withの名前を指定しても、Swift側のコードを呼び出せない

具体的に

Build時にapplication-Swift.hは更新される。WithTarget付きに。

login.swift
    func isLoggedin(target: UIViewController) -> Bool {
application-Swift.h
- (BOOL)isLoggedinWithTarget:(UIViewController * _Nonnull)target;

isLoggedinWithTargetってメソッド名にすると、 .hファイル内で isLoggedinWithTargetWithTarget になるから笑えた。

何故勝手にWithがつくのか

  • Swift3での仕様変更

最初のラベルを含むすべてのパラメータにわたって一貫したラベルの挙動を確立

どうすればいいのか

Impact on Existing Code に紹介されているうちの一つでうまくいく。

・ Function declarations that do not include explicit first item external labels will explicitly remove the first argument's label (e.g. func foo(x: Int, y: Int) will translate to func foo(_ x: Int, y: Int)).

具体的に

変更前

login.swift
    func isLoggedin(target: UIViewController) -> Bool {
application-Swift.h
- (BOOL)isLoggedinWithTarget:(UIViewController * _Nonnull)target;

変更後

login.swift
    func isLoggedin(_ target: UIViewController) -> Bool {
application-Swift.h
- (BOOL)isLoggedin:(UIViewController * _Nonnull)target;

最後に

Xcode8になっても、まだSwiftとObjCが混在するプロジェクト扱うとかやばいのではないかと思ってます。Better Translation of Objective-C APIs Into Swift
Swiftに書き換えしたい。

migrationに従ってれば問題無いのではないでしょうか。
たぶん、 FIXME: とか付くのかな・・・?

参考

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2