앱을 개발하다 보면 다양한 알림(Alert)을 사용자에게 보여줘야 하는 상황이 자주 발생한다.
예를 들어 입력값이 비었을 때, 이미 작성된 데이터가 있을 때, 또는 이미지 업로드 개수를 초과했을 때 등 여러 가지 경우가 있다.
기존에는 각 상황마다 showAlert(title:message:)
를 직접 호출하며 title과 message를 반복적으로 입력해야 했다. 하지만 이런 방식은 코드의 중복이 많아지고, 관리가 어렵다. 이를 해결하기 위해 AlertMessage Enum을 활용하면 가독성을 높이고 유지보수를 쉽게 할 수 있다.
func showEmptyTextAlert() {
showAlert(
title: "행복 기록이 없습니다",
message: "내용을 입력해주세요!"
)
}
func showImageLimitAlert() {
showAlert(
title: "이미지를 추가할 수 없습니다.",
message: "하나의 글에 최대 한 개의 이미지만 \n 추가할 수 있습니다."
)
}
위 문제를 해결하기 위해 Enum을 활용해 title과 message를 한 곳에서 관리한다.
/// 알림 메시지를 관리하는 Enum
enum AlertMessage {
case emptyText
case imageLimit
case alreadyWrittenToday
/// 각 case에 대한 title과 message 제공
var title: String {
switch self {
case .emptyText:
return "행복 기록이 없습니다"
case .imageLimit:
return "이미지를 추가할 수 없습니다."
case .alreadyWrittenToday:
return "오늘의 소확행 작성 완료!"
}
}
var message: String {
switch self {
case .emptyText:
return "내용을 입력해주세요!"
case .imageLimit:
return "하나의 글에 최대 한 개의 이미지만 \n 추가할 수 있습니다."
case .alreadyWrittenToday:
return "내일 또 당신의 소소한 행복을 작성해주세요"
}
}
}
기존에 showAlert(title:message:)
를 사용하던 부분을 AlertMessage Enum을 활용해 더 간결하게 변경할 수 있다.
func showAlert(for alert: AlertMessage) {
showAlert(title: alert.title, message: alert.message)
}
이제 showAlert(for:)
를 호출할 때 Enum의 case만 전달하면 된다.
showAlert(for: .emptyText)
showAlert(for: .imageLimit)
showAlert(for: .alreadyWrittenToday)
showAlert(for: .emptyText)
처럼 간결하게 호출할 수 있다.AlertMessage Enum을 사용하면 가독성이 좋아지고 유지보수가 편리해진다.
특히 여러 곳에서 반복되는 title과 message를 Enum에서 한 번만 정의하면 되므로, 수정이 필요할 때 한 곳만 변경하면 된다.
이 방식은 Alert뿐만 아니라, Toast 메시지, Validation 메시지 등에도 응용 가능하다.
헐 깔끔쓰