Collection ์ค Set์ ์ฌ์ฉํ๋ค๊ฐ ๋ฌธ๋, insert
์ update
์ ์ฐจ์ด๊ฐ ๋ญ์ง ๊ถ๊ธํด์ก๋ค!
Insert
Inserts the given element in the set if it is not already present.
ํด๋น ์์๊ฐ ์๋ ๊ฒฝ์ฐ ์ฝ์
@discardableResult mutating func insert(_ newMember: Element) -> (inserted: Bool, memberAfterInsert: Element)
์ฅ? ํํ์ ๋ฆฌํดํ๋ ๊ฒ์ ๋ณผ ์ ์๋ค. ์ํ ๊ทธ๋ฌ๋ฉด ๋ด๊ฐ ์์๋ฅผ insert ํ์ ๋, ์ ๋ง ๋ค์ด๊ฐ๋์ง ์๋ค์ด๊ฐ๋์ง ํ์ธํด๋ณผ ์ ์๊ฒ ๋ค.
var testSet: Set<String> = ["wansook", "bansook", "egg"]
print(testSet.insert("iOS"))
print(testSet.insert("wansook"))
(inserted: true, memberAfterInsert: "iOS")
(inserted: false, memberAfterInsert: "wansook")
์์๊ฐ ์๋ ๊ฒฝ์ฐ์๋ ์ ๋ค์ด๊ฐ๊ณ , ์๋ ๊ฒฝ์ฐ์๋ ๋ค์ด๊ฐ์ง ์์์์ ๋ช ํํ๊ฒ ํ์ธํ ์ ์์๋ค.
Update
Inserts the given element into the set unconditionally.
๋ฌด์กฐ๊ฑด์ ์ผ๋ก ์ฝ์
@discardableResult mutating func update(with newMember: Element) -> Element?
์ํ์ด ๋ค๋ฅด๋ค. ๋ฌด์กฐ๊ฑด์ ์ผ๋ก ์ฝ์ ํ๊ธฐ ๋๋ฌธ์, ์ฆ ์๋ก์ด ๊ฐ์ผ๋ก ๋์ฒด๋๋ค. ์ด๋ก์ธํด ๋ฐํ๋๋ ๊ฐ์ ํญ์ โ์ ๊ฐโ์ด๋ค. ๊ทธ๋ฐ๋ฐ ๋ฐํ ๊ฐ์ด Optional์ธ๋ฐ?
๊ทธ๋ ๋ค๋ฉด ์ธ์ ์ ๊ฐ์ ๋ฐํํ๊ณ ์ธ์ nil์ ๋ฐํํ ๊น?
var testSet: Set<String> = ["wansook", "bansook", "egg"]
print(testSet.update(with: "iOS"))
print(testSet.update(with: "wansook"))
nil
Optional("wansook")
์ํ! Set์ ์๋ ์์๋ฅผ updateํ๋ ๊ฒฝ์ฐ, nil์ ๋ฐํํ๊ณ , ์ด๋ฏธ ์์ ๊ฒฝ์ฐ ๋์ฒด๋ ๋ ์์ ๋ฐํํ๋ค.
์ฆ, ์๋กญ๊ฒ ๋ฐํ๋์์ ๊ฒฝ์ฐ, ๊ทธ ์์๋ฅผ ๋ฐํํ๋ค. ์๋กญ๊ฒ ๋ฐํ๋์ง ์์ ๊ฒฝ์ฐ์๋ nil์ ๋ฐํํ๋ค.
๋ง๋ฌด๋ฆฌ
์๊ฐ๋ณด๋ค ๋ณ ๊ฒ ์์ ์ค ์์์ง๋ง ๋ด๋ถ ๋์์ด ๋ฌ๋ผ์ ์ ์ ํ๋ค. ๋!