0
0

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]initの中でfactory methodで生成したインスタンスを返す

Last updated at Posted at 2018-02-26

*コメント欄にてloveeさんから補足を頂いているのでご覧ください!

実行コード
https://iswift.org/playground?BJSCvA&v=3

struct User {
    let id: Int
}

struct UserFactory {
    static func make(id: Int) -> User {
        return User.init(id: id)
    }
}

extension User {
    init() {
        self = UserFactory.make(id: 999)
    }
}


let user1 = User(id: 100)
let user2 = UserFactory.make(id: 101)
let user3 = User()

print(user1.id)
print(user2.id)
print(user3.id)

self = instance
で、instanceを返す事ができる。出来ないと思ってたわ…。

0
0
4

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?