Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Dictionary default value 사용 #69

Closed
kimkyuchul opened this issue May 23, 2024 · 0 comments
Closed

Dictionary default value 사용 #69

kimkyuchul opened this issue May 23, 2024 · 0 comments
Assignees
Labels

Comments

@kimkyuchul
Copy link
Owner

kimkyuchul commented May 23, 2024

dictionary default value 사용

    var dic = [String: Int]()
	      
    for i in stringArray {
        dic[i] += 1
    }
  • dic[i] += 1은 딕셔너리에 해당 키가 없을 때 에러를 발생
var dic = [String: Int]()

for i in stringArray {
    if let count = dic[i] {
        dic[i] = count + 1
    } else {
        dic[i] = 1
    }
}
  • 키가 딕셔너리에 있는지 확인하고, 존재하면 값을 증가시키며, 존재하지 않으면 값을 1 을 설정하도록 분기처리 할 수 있지만,
var favoriteTVShows = ["Red Dwarf", "Blackadder", "Fawlty Towers", "Red Dwarf"]
var favoriteCounts = [String: Int]()

for show in favoriteTVShows {
    favoriteCounts[show, default: 0] += 1
}
  • Swift 딕셔너리의 default 속성을 사용하는 방법이 더 간결하다.

https://stackoverflow.com/questions/32415188/swift-dictionary-default-value
https://developer.apple.com/documentation/swift/dictionary/subscript(_:default:)

@kimkyuchul kimkyuchul self-assigned this May 23, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant