8
7

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でネームスペースを付ける方法

Posted at

Swiftにはネームスペースがない!

Objective-Cに無いのでSwiftにも無いのだろう。
でも、たまに使いたくなる。

今回は思いつかなかったので、そのままフラットに進めてしまったけどextensionを使えばネームスペースっぽいことができるなと思ったのでメモしておく。

インナークラスを作る

Swiftではインナークラスが作れる。
なので、

NameSpace.swift
class NameSpace: NSObject {
    class Hoge {
        func test() {
            print("foo")
        }
    }
}

と記載すれば

let hoge = NameSpace.Hoge()
hoge.test()

と、呼び出せてネームスペースっぽい。

ファイルを分けたい

当然だけど、この方法で進めてしまうと全てのクラスを同じファイルに書かなければなら無いので現実的では無い。
大本のNameSpaceクラスとは別のファイルで子クラスを定義したいならextensionを使って以下のように書く。

NameSpace.swift
extension NameSpace {
    class Hoge {
        func test() {
            print("foo")
        }
    }
}

これで擬似的にネームスペースができる。

なんか、書いてみるとRubyの仕組みに似てる。
Rubyもネームスペース無いもんなぁ・・・。

以上。

8
7
2

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?