프로그래머스 (Swift)/기초
[Day12-2] 첫 번째로 나오는 음수
은더기
2024. 3. 24. 13:38
문제
내 정답 코드
import Foundation
func solution(_ num_list:[Int]) -> Int {
for i in 0..<num_list.count {
if num_list[i] < 0 {
return i
}
}
return -1
}
#
1. 단순하게 반복문을 돌리다가 0보다 작은 값이 있으면 해당 인덱스를 반환하면 된다.
재미로 더 짧은 코드로 짜보았다.
import Foundation
func solution(_ num_list:[Int]) -> Int {
let filter_num_list = num_list.enumerated().filter { $0.element < 0 }.map { Int($0.offset) }
return filter_num_list.isEmpty ? -1 : filter_num_list[0]
}
배운 기술