An Introduction to Functional Programming in Swift | raywenderlich.com

In this tutorial you’ll learn, step by step, how to get started with functional programming and how to write declarative, rather than imperative, code.


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

Hi there! I think there is a typo here in the code in Map section, where you’re providing example of re-implementation of sortedNamesImp(_:) as sortedNamesFP(_:).

func sortedNamesFP(_ rides: [Ride]) → [String] {
let rideNames = parkRides.map { $0.name }
return rideNames.sorted(by: <)
}

i think there should be:
let rideNames = rides.map { $0.name }

@dmikha Thanks very much for your question!

I believe the code in the article is correct.

parkRides is an array of Ride objects, which contains a “name” property. This array is declared earlier in the article as a let (i.e. immutable) object.

I hope this helps!

All the best.

@syedfa Thanks for reply!
I’m new to Swift and programming, so could be i didn’t figure out it correctly. But still I have some doubts.
this function is assigned to constant in the article:

let sortedNames2 = sortedNamesFP(parkRides)
testSortedNames(sortedNames2)

in the case there is no typo in original code, then function works regardless of what i give as parameter. In below example if i pass empty array, the value of constant is the same in my playground.

let sortedNames2 = sortedNamesFP()
testSortedNames(sortedNames2)

Hi Denis

You are correct. There is a bug in that function in that it’s using the externally defined variable instead of the passed through array. The correct version should be

func sortedNamesFP(_ rides: [Ride]) -> [String] {
  let rideNames = rides.map { $0.name }
  return rideNames.sorted(by: <)
}

Thanks for reply Warren,
now it’s clear.

This tutorial is more than six months old so questions are no longer supported at the moment for it. Thank you!