Swift/문법
Swift 구조체(Struct)
지용빡
2021. 12. 23. 22:39
반응형
구조체
- Memberwise Initializer가 자동으로 만들어짐
- Int, Double, String 등 기본 자료형은 구조체
- Array, Dictionart, Set은 Generic Structure
- nil도 구조체
- 구조체/enum의 인스턴스 값(value) 타입, 클래스의 인스턴스는 참조(reference) 타입
- 구조체는 상속 불가
Memberwise Initializer 자동 생성
struct Resolution { // 구조체 정의
var width = 1024 // 프로퍼티
var height = 768
}
let myComputer = Resolution() // 인스턴스 생성
print(myComputer.width) // 프로퍼티 접근
struct Resolution {
var width : Int
var height : Int
}
let myComputer = Resolution(width: 1920, height: 1080) // Memberwise Initializer
print(myComputer.width)
class Resolution {
var width : Int
var height : Int
init(width: Int, height: Int) { // class는 init으로 초기화 시켜준다.
self.width = 1920
self.height = 1080
}
}
let myComputer = Resolution(width: 1920, height: 1080) // Memberwise Initializer
print(myComputer.width)
클래스 내에 구조체
struct Resolution {
var width = 1024
var height = 768
}
class VideoMode {
var resolution = Resolution()
var frameRate = 0.0
}
let myVideo = VideoMode()
print(myVideo.resolution.width) // 1024
Swift 기본 데이터 타입은 모두 구조체
- public struct Int
- public struct Double
- public struct String
- public struct Array<Element>
- 모듈(앱)의 모든 소스 파일 내에서 사용할 수 있으며, 정의한 모듈을 가져오는 다른 모듈의 소스파일에서도 사용 가능
참고 문헌 : iOS 프로그래밍 실무 한성현 교수님 강의 내용 변형 및 요약
반응형