5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Optionalを含んだクロージャ引数があるSwiftメソッドをObjective-Cから使おうとしたらエラーが出たので回避した

Last updated at Posted at 2019-07-09

nilかそうでないかで処理を分けるために、クロージャの引数をOptionalにしたSwiftのメソッドがあったのですが、
Objective-Cから使用するために@objc属性を付加したら、エラーが出て使えませんでした。

エラー内容

Method cannot be marked @objc because the type of the parameter 4 cannot be represented in Objective-C

🙅‍♂️エラーが出たメソッド定義

ViewController.swift
@objc public func go(completion: (SomeType?) -> ())

🙆‍♂️エラー回避のための代替策

引数と戻り値を囲み、クロージャ自体をOptionalにする

ViewController.swift
@objc public func go(completion: ((SomeType) -> ())?)

引数をOptionalにすることを諦める

ViewController.swift
@objc public func go(completion: (SomeType) -> ())

この時の選んだ回避策

実際に行った回避策としては、クロージャを2つに分けました。

ViewController.swift
@objc public func go(success: (SomeType) -> (), failure: (SomeType) -> ())

あまり、遭遇機会もないかと思いますが、備忘録として書き残しておきます。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?