231128 TIL_ 데이터 타입

ykyo·2023년 11월 28일
0

데이터 타입

  • Int
    -정수를 표현하는 데이터 타입
var age: Int = 18
  • Float
    -소수점을 표현하는 데이터 타입, 32비트 부동 소수를 표현
    -정밀도: 소수점 이하 6자리까지 가능
var interestRate: Float = 1.2345678910
print("이자율은 \(interstRate) % 입니다.")
//출력값 : 이자율은 1.2345679 % 입니다.
  • Double
    -소수점을 표현하는 데이터타입, 64비트 부동 소수를 표현
    -정밀도: 소수점 이하 15자리 이상 가능
    -두 유형 모두 적합한 상황에서는 Double을 사용하는 것이 좋다(출처: 공식 문서)
var interestRate: Double = 1.2345678910123456789 
print("이자율은 \(interstRate) % 입니다.")
//출력값 : 이자율은 1.23456791023457 % 입니다.
  • Bool
    -참(true)과 거짓(false)을 표현할 수 있는 데이터 타입
var isOpen: Bool = true
var isLogged: Bool = false

if isOpen{
	print("문이 열려 있습니다.")
}
else{
	print("문이 닫혀 있습니다.")
}

func checkLoginStatus(is Logged: Bool){
	if is Logged{
    	print("로그인 되었습니다.")
    }
    else{
    	print("로그인되지 않았습니다.")
    }
}
  • String
    -문자열을 표현하는 데이터타입. 텍스트를 표현한다.
var emptyString: String = "" //빈 스트링 선언
var anotherEmptyString = String() //빈 스트링 선언. 위와 같음

var variableString = "Mom"
variableString += " and Dad"
print(variableString)

//출력값 : "Mom and Dad"
  • Character
    -하나의 문자를 표현하는 데이터 타입
let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"]
let catString = String(catCharacters)
print(catString)

//출력값 : "Cat!🐱"
  • Tuple
    -튜플은 여러 값을 하나로 그룹화한 것
    -관련 값의 단순한 그룹에 유용. 복잡한 데이터 구조를 만드는 데는 적합하지 않음.
let http404Error: (Int, String) = (404, "Not Found")

let (justTheStatusCode, _): (Int, String) = http404Error //_ 는 사용하지 않는단 의미.
print("The status code is \(justTheStatusCode)")
//출력값: "The status code is 404"

//튜플 값에 접근하려면 순서를 알고 있어야 함.
print("The status code is \(http404Error.0)")
//출력값: "The status code is 404"
print("The status code is \(http404Error.1)")
//출력값: "The status code is Not Found"

//각 엘레먼트에 이름을 붙일 수 있다.
let http200Status: (Int, String) = (statusCode: 200, description: "Ok")

//많은 데이터를 담는 데는 적합하지 않다. 사용하는 쪽에서 또 매핑을 해야 함
let myInfo: (String, Int, Int, Int, String, String) =
(name: "Peter", registrationNumber: 970212, height: 185, weight: 75, job: "developer")
  • Any
    -Any는 다양한 데이터 타입의 값을 수용할 수 있다.
    -Any 배열을 만들면 특정 타입의 배열이 아니라 여러 타입을 담을 수 있다.
    -하지만 Any 데이터 형을 대입하려면 반드시 형 변환이 필요하다.
var anyArray: [Any] = [1,"Hi",true]

var anyValue: Any = 1000
anyValue = "어떤 타입도 수용 가능"
anyValue = 12345.67

//컴파일 에러
let doubleValue: Double = anyValue
//Any 타입에 Double 값을 넣는 것은 가능하지만
//Any는 Double과 엄연히 다른 타입이기 때문에
//Double 타입의 값에 Any 타입의 값을 할당할 때에는 명시적으로 타입을 변환해 주어야 한다.
profile
for ios, swift, etc.

0개의 댓글