Skip to content

Instantly share code, notes, and snippets.

let contactsDurationArr = contacts.map({ return $0.duration })//We use the map function to derive an array that contains only the duration property of all the objects
var sum = 0
for duration in contactsDurationArr {
sum = sum + duration
}
print(sum)
//Functional Programming
let contactsAbove20 = contacts.filter({ $0.age > 20 })
print(contactsAbove20)
//Imperative Programming
func filterContacts(aboveAge age: Int) -> [Contact] {
var filteredContacts = [Contact]()
for contact in contacts {
if contact.age > age {
filteredContacts.append(contact)
}
}
return filteredContacts
}
//Functional Programming
let contactNames = contacts.map({
return $0.firstName + " " + $0.lastName
})
print(contactNames)
//Get just the name of the contacts into a separate array
//Imperative Programming
var contactNamesImp = [String]()
for contact in contacts { // for each
contactNamesImp.append(contact.firstName)
}
print(contactNamesImp)
let contacts = [
Contact(firstName: "first", lastName: "1", email: "some@one1.com", age: 20, courseDuration: 12),
Contact(firstName: "Second", lastName: "2", email: "some@one2.com", age: 22, courseDuration: 16),
Contact(firstName: "Third", lastName: "3", email: "some@one3.com", age: 30, courseDuration: 22)
]
struct Contact {
var firstName: String
var lastName: String
var email: String
var age: Int
var duration: Int
}
//Functional Programming
func sum(start: Int, end: Int, total: Int) -> Int {
if (start > end) {
return total;
}
return sum(start: start + 1, end: end, total: total + start)
}
print("Functional: total: ", sum(start: 1, end: 10, total: 0)); // prints 55
//Imperative Programming
var total = 0
for i in 1...10 {
total += i
}
print("Imperative: total: ", total); // prints 55
func add(x, y) {
return x + y
}