728x90
반응형
import Cocoa
//Class
// 구조체 타입을 정하는 것이다.
class Sample {
var sampleProperty: Int = 10 // 가변 Property
let fixedSampleProperty: Int = 100 // 불편 Property
static var typeProperty: Int = 1000 // 타입 Property
func instanceMethod() {
print("instance method")
}
//타입 메서드
// 재정의 불가 타입 메서드 - static
static func typeMethod() {
print("type method-static")
}
// 재정의 기능 타입 메서드 - class
class func classmethod(){
print("type method-class")
}
}
// 인스턴스 생성
var samp: Sample = Sample()
samp.sampleProperty = 200
print(samp.sampleProperty)
let samp2: Sample = Sample() // 서로 다른 인스턴스가 있다. samp ,samp2
samp2.sampleProperty = 500
print(samp2.sampleProperty)
print(samp.sampleProperty)
samp = samp2 // 참조가 서로 같아지는 경우
print(samp2.sampleProperty)
print(samp.sampleProperty)
// 보통 클래스는 let으로 쓴다.
Sample.typeProperty = 300 // Class에서 받아서 쓰는 것
print(Sample.typeProperty)
Sample.typeMethod()
// Sample. typeProperty 는 바뀔 수가 없다. (어떤 것 때문에)
// 학생 클래스
class Student{
var name: String = "unknown"
var `class`: String = "Swift"
class func selfIntroduce(){ // 타입 메서드
print("학생 타입 입니다.")
}
// 일반적
func selfIntroduce(){
print("저는 \(self.class)반 \(name)입니다.")
}
}
// 타입 메서드 사용
Student.selfIntroduce()
// 인스턴스
var student: Student = Student()
student.name = "james"
student.class = "Swift"
student.selfIntroduce()
let cathy: Student = Student()
cathy.name = "Cathy"
cathy.selfIntroduce()
// ----------------
// Class & Struct
// ----------------
struct Resolution {
var width = 0
var hegight = 0
}
class VideoMode{
var resolution = Resolution()
var interlaced = false // 비디오 관련된 코드
var frameRate = 0.0
var name: String?
}
let someResolution = Resolution() // 구조체 인스턴스
let someVideoMode = VideoMode() // 클래스 인스턴스
print("The width of someVideoMode is \(someVideoMode.resolution.width)")
someVideoMode.resolution.width = 1280
print("The width of someVideoMode is \(someVideoMode.resolution.width)")
print(someResolution.width) // struct per by value != reference가 아니다.
// 위에 값과는 다르다.
// 구조체의 멤버 초기화
let vga = Resolution(width: 640, hegight: 480)
var cinema = vga
print("cinema is now \(cinema.width) pixels")
//
반응형
'개발자 코드(Code) > Swift(문법)' 카테고리의 다른 글
Swift) 13_Closure (0) | 2020.09.24 |
---|---|
Swift) 12_열거형 (0) | 2020.09.24 |
Swift) 10_Struct (0) | 2020.09.24 |
Swift) 09_값타입과 참조타입 (0) | 2020.09.24 |
Swift) 08_옵셔널.Playground (0) | 2020.09.24 |