Swift/개념 & 응용

[Swift] Swift 문법 - 자료형(Bool, Int, Float, Double, Character, String, Tuple)

유정주 2021. 8. 16. 00:10
반응형

안녕하세요. 

 

오늘은 Swift의 자료형인 Bool, Int, Float, Double, Character, String, Tuple에 대해 알아보겠습니다.


참고 자료

Apple Swift Document

https://developer.apple.com/documentation/swift

 

해당 포스팅은 Smile Han님의 유튜브 영상을 참고하며 작성하였습니다.

https://www.youtube.com/channel/UCM8wseo6DkA-D7yGlCrcrwA


 

Bool

A value type whose instances are either true or false.

true와 false 값만 가질 수 있습니다.

참과 거짓을 나타냅니다.

 

Int

A signed integer value type.

정수를 저장하는데 사용합니다.

 

양수, 음수, 0 값을 가질 수 있는 signed 정수와

음수를 가질 수 없는 unsigned 정수로 나뉩니다.

 

비트에 따라 Int8, Int16, Int32, Int64로 나뉘며

unsigned는 UInt8, UInt16, UInt32, UInt64로 나뉩니다.

 

Swift의 Int는 플랫폼에 따라 자동으로 Int의 bit를 결정합니다.

직접 명시할 수도 있지만 권장사항은 아닙니다.

 

Int의 범위는 아래와 같습니다.

print("Int8 min: \(Int8.min), max: \(Int8.max)")
print("Int16 min: \(Int16.min), max: \(Int16.max)")
print("Int32 min: \(Int32.min), max: \(Int32.max)")
print("Int64 min: \(Int64.min), max: \(Int64.max)")

print("--------------------------------------------")

print("UInt8 min: \(UInt8.min), max: \(UInt8.max)")
print("UInt16 min: \(UInt16.min), max: \(UInt16.max)")
print("UInt32 min: \(UInt32.min), max: \(UInt32.max)")
print("UInt64 min: \(UInt64.min), max: \(UInt64.max)")

 

Float

A single-precision, floating-point value type.

소수점이 있는 숫자를 저장합니다.

32비트로 소수점 6자리 정확도를 가집니다.

 

Double

A double-precision, floating-point value type.

소수점이 있는 숫자를 저장합니다.

64비트로 소수점 15자리 정확도를 가집니다.

 

Swift의 부동소수점 타입 추론은 Double로 됩니다.

let t = 10.0
print(type(of: t))

 

Character

A single extended grapheme cluster that approximates a user-perceived character.

문자, 숫자, 문장 부호, 심볼같은 유니코드 문자 하나를 저장합니다.

 

Swift의 문자 타입 추론은 String이 기본이므로 character형을 쓰기 위해선 직접 명시해야 합니다.

유니코드를 사용하기 때문에 한글, 이모티콘도 사용 가능합니다.

let 한글변수 = 10
print(한글변수)

let 😀 = 20
print(😀)

 

String

A Unicode string value that is a collection of characters.

단어나 문장을 저장합니다.

 

String 여러 줄은 """를 이용해서 초기화가 가능합니다.

let banner = """
          __,
         (           o  /) _/_
          `.  , , , ,  //  /
        (___)(_(_/_(_ //_ (__
                     /)
                    (/
        """
print(banner)

 

Tuple

A tuple type is a comma-separated list of types, enclosed in parentheses.

Swift에서는 파이썬처럼 Tuple을 기본으로 제공합니다.

여러 값을 하나의 객체에 묶는 방법입니다.

index 혹은 key값으로 특정 튜플 값 참조가 가능합니다

let tuple = (t1: 1,t2: 2,t3: 3)
print(tuple.0)
print(tuple.t1)

튜플 전체를 대입할 때 사용하지 않는 키가 있다면 _로 작성하면 됩니다.

let tuple = (t1: 1,t2: 2,t3: 3)
let (tuple1, _, tuple3) = tuple
print(tuple1)

 

튜플의 최고 장점은 함수에서 여러 값을 한 번에 반환할 수 있다는 점입니다.

함수를 학습할 때 다시 말씀드리겠습니다.

 

감사합니다!


아직은 초보 개발자입니다.

더 효율적인 코드 훈수 환영합니다!

공감 댓글 부탁드립니다.

 

 

반응형