// Void는 생략 가능
func sayHello() -> Void {
print("안녕하세요")
}
func sayHello() {
print("안녕하세요")
}
sayHello()
func sayHello2() -> String {
return "안녕"
}
print("자기소개: \(sayHello2())")
func bmiResult() -> [String] {
let name = "고래밥"
let result = "정상"
return [name, result]
}
let value = bmiResult()
print(value[0] + "님의 BMI 지수는 " + value[1] + "입니다.")
let userInfo: (String, String, Bool, Double) = ("고래밥", "jack@jack.com", true, 4.5)
// 순서대로 요소를 가져올 수 있음
print(userInfo.0)
print(userInfo.1)
func loginGame() -> (Int, String) {
return (333, "도적")
}
let value = loginGame()
print("레벨 \(value.0)인 \(value.1)이 로그인하셨습니다.")
func getMovieReport2() -> (Int, Int) {
(1000, 30000)
}
@discardable
키워드를 작성해주면 return값을 사용하지 않아도 경고가 뜨지 않는다.enum AppleDevice {
case iPhone
case iPad
case watch
}
런타임
시점에서 오류를 확인할 수 있지만 열거형은 컴파일
오류로 바로 확인할 수 있기 때문에 버그 수정하기 훨씬 편리하다.enum HTTPCode: Int {
case OK = 200
case SERVER_ERROR = 500
case NO_PAGE
func showStatus() -> String {
switch self {
case .NO_PAGE:
return "잘못된 주소입니다."
case .SERVER_ERROR:
return "서버 점검중입니다. 서버에 문제가 생겨서 잠시 후 시도해주세요."
case .OK:
return "정상입니다."
}
}
}
var status: HTTPCode = .OK
print(status.rawValue) // 값이 부여되지 않았으면 순서대로 0, 1, 2, .. 등등 int가 자동으로 부여됨
status.showStatus() // 정상입니다
enum GameJob: String {
case rogue = "도적"
case warrior = "전사"
case mystic = "도사"
case shaman
case fight
}
let selectJob: GameJob = GameJob.mystic
// let selectJob: GameJob = .mystic (타입이 명확하게 선언돼있으면 GameJob 생략가능함)
print("당신은 \(selectJob.rawValue)입니다.") // 도사
enum School: Int {
case elementary
case middle
case high = 300
case university
}
print(school.elementary.rawValue) // 0
print(school.middle.rawValue) // 1
print(school.high.rawValue) // 300
print(school.university.rawValue) // 301
Authorization -> Request -> Notification
Authorization: Alert, Badge, Sound
Request: Content(title, body, badge), Trigger(time(시간간격), calendar(보내고 싶은 날짜 및 시간), location)
func requestNotificationAuthorization() {
// 권한에 대한 항목
let authOptions = UNAuthorizationOptions(arrayLiteral: .alert, .badge, .sound)
userNotificationCenter.requestAuthorization(options: authOptions) { success, error in
if success {
self.sendNotification()
}
}
}
정보
와 관련된 클래스Identifier
알림을 구분하는 고유한 값으로 Identifier가 동일하다면 알림 내용이 수정되는 형태로 동작한다.
만약 Identifier가 다르다면 스택 형태로 알림이 쌓인다.
func sendNotification() {
// 어떤 정보를 보낼지 컨텐츠 구성
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "물 마실 시간이에요!"
notificationContent.body = "하루 2리터 목표 달성을 위해 열심히 달려보아요"
notificationContent.badge = 100
// 언제 보낼지 설정: 1. 간격, 2. 캘린더, 3. 위치
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true)
let request = UNNotificationRequest(identifier: "\(Date())",
content: notificationContent,
trigger: trigger)
userNotificationCenter.add(request) { error in
if let error = error {
print("Notification Error: ", error)
}
}
}
@IBAction func buttonTapped(_ sender: UIButton) {
// 1. UIAlertController 생성: 밑바탕 + 타이틀 + 본문
let alert = UIAlertController(title: "타이틀입니다", message: "메세지입니다", preferredStyle: .actionSheet)
// 2. UIAlertAction 생성: 버튼들
let ok = UIAlertAction(title: "OK", style: .default)
let cancel = UIAlertAction(title: "cancel", style: .cancel)
let delete = UIAlertAction(title: "delete", style: .destructive)
// 3. 1, 2번 합쳐주기
alert.addAction(ok)
alert.addAction(cancel)
alert.addAction(delete)
// 4. 화면 띄워주기
present(alert, animated: true, completion: nil)
}