VesselWheel

서울에서 김서방 찾기 본문

Coding Test Practice in Swift

서울에서 김서방 찾기

JasonYang 2023. 11. 22. 09:48

문제

 

 

풀이

 

func solution(_ seoul:[String]) -> String {

    return "김서방은 \(seoul.firstIndex(of: "Kim")!)에 있다"
}

 

 TIP

firstIndex(of:)

Returns the first index where the specified value appears in the collection.
iOS 8.0+ iPadOS 8.0+ macOS 10.10+ Mac Catalyst 13.0+ tvOS 9.0+ watchOS 2.0+ visionOS 1.0+ Beta
func firstIndex(of element: Self.Element) -> Self.Index?
Available when Element conforms to Equatable.

Parameters 

element

An element to search for in the collection.

Return Value

The first index where element is found. If element is not found in the collection, returns nil.

Discussion

After using firstIndex(of:) to find the position of a particular element in a collection, you can use it to access the element by subscripting. This example shows how you can modify one of the names in an array of students.

var students = ["Ben", "Ivy", "Jordell", "Maxime"]
if let i = students.firstIndex(of: "Maxime") {
    students[i] = "Max"
}
print(students)
// Prints "["Ben", "Ivy", "Jordell", "Max"]"

'Coding Test Practice in Swift' 카테고리의 다른 글

음양 더하기  (0) 2023.11.22
나누어 떨어지는 숫자 배열  (0) 2023.11.22
콜라츠 추측  (0) 2023.11.22
두 정수 사이의 합 with reduce 함수  (1) 2023.11.21
정수 내림차순으로 배치하기  (1) 2023.11.21