LoginSignup
5
3

More than 5 years have passed since last update.

Swift で `Method cannot be marked @objc because its result type cannot be represented in Objective-C` が出るもクラスの定義がライブラリ内なとき

Posted at

swift 4

課題

とかにあるように、 @objc 修飾子をつけた場合、定義されているクラスは Objective-C から見られるよう NSObject を継承しなければならない

が、この例でいう User が、自分が定義しているクラスじゃないときは、

class User: NSObject

と書くことは当然できない。

解決策(の一例)

方針としては、

  • objc 修飾子をつけたい func では、 Objective-C で解決できるようなものを指定する
  • 必要であれば、 Swift 側で、それを適切に戻してあげる

たとえば enum State: String を受け取りたい callback の protocol があるとして、

@objc protocol SomethingDelegate {
    @objc optional
    func callback(state: String?, error : Error?)

のように、 State ではなく String で定義する。で、 Objective-C に渡す callback を swift 上では、下記のように書いてあげる

            callback: { (state: State?) in
                delegate.callback?(state: state?.rawValue, error: error)
            }

すると、 Method cannot be marked @objc because its result type cannot be represented in Objective-C を言われずに済む。

載せられるコードだけ部分的に載せたから、いい例になってなかったらごめんなさい。

5
3
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
5
3