Kodeco Forums

Introduction to Functional Programming in Swift

Learn how to use functional programming in Swift, and the concepts of immutability, modularity, first-class and higher-order functions, and more.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/1423-introduction-to-functional-programming-in-swift

So for anyone else looking how to convert the initial imperative implementation to Swift 3 compatible code, here is what I did:

func sortedNames(rides: [Ride]) → [String] {
var sortedRides = rides

// 1 - Looping over all the rides passed into the function
for (index, sortedRide) in sortedRides.enumerated() {
// 2 - Performing an insertion sort
for j in stride(from: index, to: -1, by: -1) {
if sortedRide.name.localizedCompare(sortedRides[j].name) == .orderedAscending {
sortedRides.remove(at: j + 1)
sortedRides.insert(sortedRide, at: j)
}
}
}

// 3 - Gathering the names of the sorted rides
var sortedNames = String
for ride in sortedRides {
sortedNames.append(ride.name)
}

// print(sortedRides)

return sortedNames
}

func quicksort<T: Comparable>(var elements: [T]) -> [T] {
    if elements.count > 1 {
        let pivot = elements.removeAtIndex(0)
        return quicksort(elements.filter { $0 <= pivot }) + [pivot] + quicksort(elements.filter { $0 > pivot })
    }
    return elements
}

…produce an error “parameters may not have the ‘var’ specifier
func quicksort<T: Comparable>(var elements: [T]) → [T] {”

This tutorial is more than six months old, so questions regarding it are no longer supported for the moment. We will update it as soon as possible. Thank you! :]