Restrição com cláusula where em Swift
Nível 5664 toques
Cláusulas where adicionam restrições a parâmetros genéricos. findLatest exige que T esteja em conformidade com Identifiable e Timestamped e retorna o elemento com o maior timestamp, imprimindo Latest: End at 200.
Código Swift
// Dois protocolos pequenos, cada um com um requisito de propriedade1protocol Identifiable {2 var id: String { get }3}4 5protocol Timestamped {6 var timestamp: Int { get }7}8 // Event está em conformidade com os dois protocolos9struct Event: Identifiable, Timestamped {10 var id: String11 var timestamp: Int12 var name: String13}14 // where T: Identifiable & Timestamped exige os dois protocolos15func findLatest<T>(_ items: [T]) -> T? where T: Identifiable & Timestamped { // max(by:) retorna o elemento com o maior timestamp (nil se estiver vazio)16 return items.max(by: { $0.timestamp < $1.timestamp })17}18 // Combina uma restrição inline com uma cláusula where; não é chamada (Event não é Equatable)19func findById<T: Identifiable>(_ items: [T], id: String) -> T? where T: Equatable { // Retorna o primeiro elemento com o id procurado20 return items.first(where: { $0.id == id })21}22 23let events = [24 Event(id: "1", timestamp: 100, name: "Start"),25 Event(id: "2", timestamp: 200, name: "End")26]// O resultado é opcional, então é desembrulhado com if let27if let latest = findLatest(events) { // Imprime Latest: End at 20028 print("Latest: \(latest.name) at \(latest.timestamp)")29}Saída
Latest: End at 200
Pratique digitando este código. Os resultados não são registrados no ranking.
Símbolos deste código
Os símbolos que você digita neste código Swift e quantas vezes aparecem.
:× 21"× 10(× 10)× 10{× 10}× 10,× 7.× 7=× 4>× 4