๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Swift

[Swift] nil vs null

by Sky Titan 2023. 1. 7.
728x90
 

The difference between nil, Nil, NULL, and NSNull in Swift

As a programmer, sometimes you will need to define “nothingness”… ๐Ÿง Data stores can have a value, or simply be nothing, this nothing comes in different flavors (nil, Nil, Null, NSNull) which all came to be called “null”. In Swift, you will n

www.linkedin.com

 LinkedIn์— nil๊ณผ Null์˜ ์ฐจ์ด์— ๋Œ€ํ•œ ๊ธ€์ด ์˜ฌ๋ผ์™€์žˆ์–ด์„œ ์š”์•ฝํ•ด๋ณด์•˜๋‹ค.

 

 ํ”„๋กœ๊ทธ๋ž˜๋ฐ์„ ํ•˜๋ฉด์„œ '์•„๋ฌด๊ฒƒ๋„ ์—†์Œ'์„ ํ‘œํ˜„ํ•  ํ•„์š”๊ฐ€ ์žˆ๋Š”๋ฐ, ์ด ๋•Œ Objective-C์—์„  ํฌ๊ฒŒ 4๊ฐ€์ง€ ํ˜•ํƒœ์˜ ๋นˆ ๊ฐ’์„ ๋‚˜ํƒ€๋‚ด๋Š” ํ‘œํ˜„์ด ์žˆ๋‹ค.

  ์˜๋ฏธ
NULL C pointer์˜ null ๊ฐ’์„ ์˜๋ฏธ
nil Objective-C์˜ object๋“ค์„ ๋‚˜ํƒ€๋‚ด๋Š” null ๊ฐ’
Nil Objective-C์˜ class๋“ค์„ ๋‚˜ํƒ€๋‚ด๋Š” null ๊ฐ’
NSNull null์„ ํ‘œํ˜„ํ•˜๊ธฐ ์œ„ํ•œ single tone object

 Swift์—์„  NULL, Nil์€ ๋‹ค๋ฅผ ์ˆ˜ ์—†๋‹ค.

 

 Null์€ Objective-C์—์„œ object๊ฐ€ ์•„๋‹Œ, ์ฆ‰ struct์™€ ๊ฐ™์€ ํƒ€์ž…๋“ค์˜ ๋นˆ ๊ฐ’์„ ํ‘œํ˜„ํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉ๋œ pointer value์ด๊ณ , nil์€ object๋“ค์˜ ๋นˆ ๊ฐ’์„ ํ‘œํ˜„ํ•˜๊ธฐ ์œ„ํ•ด ์‚ฌ์šฉ๋œ pointer value์ด๋‹ค.

 

 ํ•˜์ง€๋งŒ Swift์—์„  Null์€ ์‚ฌ๋ผ์กŒ๊ณ , nil์€ pointer๊ฐ€ ์•„๋‹Œ, ํŠน์ •ํ•œ ํƒ€์ž…์ด ์—†์Œ์„ ๋‚˜ํƒ€๋‚ด๋Š” ๊ฐ’์œผ๋กœ ์‚ฌ์šฉ๋˜๊ณ  ์žˆ๋‹ค.

์ฆ‰ Objective-C์˜ ์ž”์žฌ๋กœ pointer๋กœ ๊ฐ์ฒด์— ์ ‘๊ทผํ•˜๋Š” ๊ฐœ๋…์ด ์‚ฌ๋ผ์ง„ Swift์— nil์ด๋ผ๋Š” ๊ฒƒ์ด ๋‚จ์•„์žˆ๊ฒŒ ๋˜์—ˆ๊ณ  ์ด๋Š” ๋‹ค๋ฅธ ์–ธ์–ด์˜ null๊ณผ ๋™์ผํ•œ ๊ฐœ๋…์ด๋ผ๊ณ  ์ดํ•ดํ•˜๋ฉด ๋œ๋‹ค.

Objective-C์—์„œ: nil์€ ์กด์žฌํ•˜์ง€ ์•Š๋Š” object๋ฅผ ๊ฐ€๋ฆฌํ‚ค๋Š” pointer
Swift์—์„œ: nil์€ pointer๊ฐ€ ์•„๋‹Œ, ํŠน์ • ํƒ€์ž…์˜ value๊ฐ€ ์—†์Œ์„ ๋‚˜ํƒ€๋‚ธ๋‹ค.

 

728x90

๋Œ“๊ธ€