1
1

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.

【swift】var geometry: [MKShape & MKGeoJSONObject] という定義を見てビックリした

1
Posted at

小ネタですが、1時間ぐらい調べてしまったので、書いときます。

あなたはわかりますか?

AppleのMapkitにGeoJSONを処理するクラスがあって、それを仕事でゴニョゴニョしています。
そんな中、こんなプロパティを見つけました。

var geometry: [MKShape & MKGeoJSONObject] { get }

これを最初見たとき、「え? 型2つあるやん!」(誤解)と焦りました。

答え

正解は、MKGeoJSONObjectはprotocolで、型はMKShapeだけです。
MKShapeはClassなので、MKGeoJSONObjectに従うClass=MKShapeという指定でした。

プロトコルコンポジションというカッコいい名前があるみたいです。
プロトコルコンポジションするときは、だいたい下記みたいに、カンマで区切るのが多いので、
今回みたいに&でつなぐパターンもあるのか〜と新発見しました。

class hoge: protocolA, protocolB,

これをプロパティの型に指定して書いてやると、

var any: [hoge & protocolA & protocolB]

こんな感じになるわけですね。
「,」区切りのときも継承クラスとの区別がわかりづらいな〜と思っていましたが、
「&」区切りだと完全に型とプロトコルが同列に並んでるように見えて、僕にはわかりづらく感じます。
慣れなんですかね?

1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?