[Elixir][Swift]ElixirやSwiftのprotocolなどの話

たまたま見つけて。

ElixirはClojureに影響されているのですね。protocol周辺の使い道。

パッと、 defimpl の対象となるタイプを思い出せなかったので以下にURLを一応。

http://elixir-lang.org/docs/stable/elixir/Kernel.html#defprotocol/2

こんな感じ。 defimpl第一引数のタイプ によって、どのタイプに対する実装かを示しています。

defprotocol JSONA do
  def to_json(data, precision)
end

defprotocol JSONB do
  def to_json(data, scale)
end

defimpl JSONA, for: BitString do
  def to_json(data, _precision) do
    "hello"
  end
end

defimpl JSONA, for: Integer do
  def to_json(data, _precision) do
    Integer.to_string(data)
  end
end

JSONA.to_json "abc", 10
|> IO.puts

Swiftは、記事のものは古いので省略。も少しあとで。

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.