[Swift] Array값 Optional로 가져오기

김정윤·2023년 3월 17일
extension Collection {

    /// Returns the element at the specified index if it is within bounds, otherwise nil.
    subscript (safe index: Index) -> Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

사용

if let item = array[safe: i] {
	// print(item)
}
profile
iOS앱개발자

0개의 댓글