Dictioary 활용법

w0308h 2월 20일 AM 10:53 4 0
w0308h Profile Image Level 9
2 #TIL

  • 딕셔너리에서 값 가져오기
for (key, value) in dict {
	print(key)
}

dict.forEach { (key: String, value: Int) in 
	print(key)
}
  • 딕셔너리 정렬하기
//value 기준 정렬
let sortedByValue = dict.sorted { $0.1 < $1.1 }

//key 기준 정렬 (오름차순)
let sortedByKey = dict.sorted { $0.0 < $1.0 }

//value를 기준으로 정렬하되, 그 값이 같은 경우 key를 기준으로 정렬
let sorted = dict.sorted {
	if $0.1 == $1.1 { return $0.0 < $1.0 }
	return $0.1 < $1.1
}
댓글