[TIL] Swift - first(where:), contains(where:), isEmpty, allSatisfy

신승현·2024년 2월 19일

TIL

목록 보기
24/72

1. first(where:)

  • filter 대신에 first(where:)를 사용해 첫번째 원소를 가져올 수 있다.
// Instead of:
if let element = array.filter { $0.title.contains(searchString) }.first {
    // do something
}

// Do:
if let element = array.first(where: { $0.title.contains(searchString) }) {
    // do something
}

2. contains(where:)

  • filter 대신에 사용이 가능한 contains(where:)이 있다.
// Instead of:
if array.filter { !$0.isActive }.count > 0 {
    // do something
}

// Do:
if array.contains(where: { !$0.isActive }) {
    // do something
}

3. isEmpty

  • 배열이 비어있는지 확인하기 위해 count로 0을 확인 하는 것보단, isEmpty를 사용하면 편하다.
// Instead of:
if array.count == 0 {
    // do something
}

// Do:
if array.isEmpty {
    // do something
}

4. allSatisfy

  • 문자열에는 allSatisfy 메서드가 있다. 메서드의 인자로 문자를 검사할 클로저를 주면 모든 문자가 조건에 만족되면 true, 한 문자라도 조건에 만족하지 않으면 false 를 반환한다.
var str = "s1234"
str.allSatisfy({ $0.isNumber }) // false
 
var str2 = "1234"
str.allSatisfy({ $0.isNumber }) // true
profile
개발자

0개의 댓글