Swift/swift 문법
스위프트 - 클로저를 사용한 프로퍼티 기본값 설정
Lyla.
2022. 9. 7. 15:07
클래스 SchoolClass의 students의 값을 클로저를 이용해 기본값 설정.
주의할 점은 클로저 작성 이후에 ()소괄호 넣어주어야 클로저의 return값으로 사용할 수 있음.
빠트리면 '클로저'자체가 값으로 들어가서 의도한 결과와 달라짐.
[예시코드]
import UIKit
struct Student {
var name: String?
var number: Int?
}
class SchoolClass {
var students: [Student] = {
var arr: [Student] = Student
for num in 1...10 {
var student: Student = Student(name: nil, number: num)
arr.append(student)
}
return arr
}()
}
let myClass: SchoolClass = SchoolClass()
print(myClass.students.count)