Created
August 7, 2025 00:44
-
-
Save kyle-morton/e388f483887a87c9bd65248db389bfba to your computer and use it in GitHub Desktop.
Swift Closures
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
struct Student { | |
var name: String | |
var testScore: Int | |
} | |
let students = [ | |
Student(name: "Ted", testScore: 84), | |
Student(name: "Todd", testScore: 79), | |
Student(name: "Tom", testScore: 93), | |
Student(name: "Terry", testScore: 71) | |
] | |
// closure syntax | |
var topStudentFilter: (Student) -> Bool = { student in | |
return student.testScore > 80 | |
} | |
func topStudentFilterFunc(student: Student) -> Bool { | |
return student.testScore > 80 | |
} | |
// hitting enter on a closure gives you 'trailing closure syntax' (much cleaner) | |
let topStudents2 = students.filter { student in // type is inferred from array | |
return student.testScore > 80 | |
} | |
let topStudents3 = students.filter { | |
$0.testScore > 80 // no return needed b/c it's a one-liner | |
} | |
print("top students (closure): \(students.filter(topStudentFilter).count)") | |
print("top students (func): \(students.filter(topStudentFilterFunc).count)") | |
print("top students (trailing closure): \(topStudents2.count)") | |
print("top students (Shorthand syntax for params): \(topStudents3.count)") | |
// The above all do the same thing, but closures allow you to reuse that bit of code wherever you need it (like an extension or a helper) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment