Skip to content

Instantly share code, notes, and snippets.

//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 contactsAbove20 = contacts.filter({ $0.age > 20 })
print(contactsAbove20)
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 totalDurationSpentByContacts = contactsDurationArr.reduce(0,+)
print(totalDurationSpentByContacts)
extension String {
/// Used to validate if the given string is valid email or not
///
/// - Returns: Boolean indicating if the string is valid email or not
func isValidEmail() -> Bool {
let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
print("emailTest.evaluate(with: self): \(emailTest.evaluate(with: self))")
return emailTest.evaluate(with: self)
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
let heyThereSequence = Observable.of("Hey there!")
let subscription = heyThereSequence.subscribe { event in
print(event)
}
Result:
next("Hey there!")
completed
let heySequence = Observable.from(["H","e","y"])
let subscription = heySequence.subscribe { event in
switch event {
case .next(let value):
print("onNext Event: \(value)")
case .error(let error):
print(error)
case .completed:
print("onCompleted")
}
let disposeBag = DisposeBag()
let heySequence = Observable.from(["H","e","y"])
let subscription = heySequence.subscribe { event in
switch event {
case .next(let value):
print("onNext, Event: \(value)")
case .error(let error):
print(error)
case .completed:
let disposeBag = DisposeBag()
//1
let behaviourRelay = BehaviorRelay<String>(value: "")
//2
let subscription1 = behaviourRelay.subscribe(onNext:{ string in
print("subscription1: ", string)
})
//3
subscription1.disposed(by: disposeBag)
//4