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์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

๋งˆ๋ฌด๋ฆฌ

์ƒ๊ฐ๋ณด๋‹ค ๋ณ„ ๊ฒƒ ์—†์„ ์ค„ ์•Œ์•˜์ง€๋งŒ ๋‚ด๋ถ€ ๋™์ž‘์ด ๋‹ฌ๋ผ์„œ ์‹ ์„ ํ–ˆ๋‹ค. ๋!

Reference