DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
The Latest "Software Integration: The Intersection of APIs, Microservices, and Cloud-Based Systems" Trend Report
Get the report
  1. DZone
  2. Coding
  3. Frameworks
  4. How Functional is Swift?

How Functional is Swift?

In this post, MVB Christopher Lamb walks us through a quick tutorial on how to functionally program in the Swift language.

Christopher Lamb user avatar by
Christopher Lamb
CORE ·
Mar. 21, 17 · Tutorial
Like (5)
Save
Tweet
Share
4.72K Views

Join the DZone community and get the full member experience.

Join For Free

Short answer: pretty functional, but not completely.

Long answer: well, keep reading!

First, let's define the kinds of attributes we're looking for when we call a functional language or runtime "functional." Some people look at map/reduce as a proxy for functional - I don't. C, a decidedly non-functional language, can do that. Some look to recurion - I think that's a big part of it. Primarily, it's the ability to use functions as first-order objects. Then, the ability to properly recurse. I like to add type safety and initial assignment-only variables, but you don't have to. So how does Swift stack up?

First, Swift certainly does allow you to use functions as first-order objects. You can create them and pass them around as variables, like any other variable in an argument list:

let static_ints = [1,2,3,4,5]
let static_strs = ["Aa", "Bb", "Cc", "Dd", "Ee"]

func printer<T>(withValue value: T) {
    print("Printed: ", value)
}

func printList<T>(withList list: [T], andPrinter printer: (_ : T) -> Void) {
    for l in list {
        printer(_: l)
    }
}

printer(withValue: 1)
printList(withList: static_ints, andPrinter: printer)

You can do this kind of thing in a variety of ways. I pass this as an argument list, however, to show that functions are treated just as any other variable would be.

It does not allow you do assign generic functions as you would regular variables (i.e.  var v = printer<Int>  ), but you can assign closures and variables without generic parameters.

So, not perfect, but not bad either.

Up next: recursion. So how does Swift fare?

We can recurse, and Swift even seems to support tail recursion. Write an eternally recursing function in a Swift playground - it won't run out of stack space if you're not allocating any:

func eternalLoop<T>(withList list: [T]) {
    eternalLoop(withList: list)
}

eternalLoop(withList: static_ints)

This means that the language and runtime are not blowing stack space setting up call frames for each function invocation - this is vital in a functional language, and Swift seems to do it.

What it doesn't do is provide syntactic support for recursion. For example, if I want to recurse successfully, I need to do something like this:

func recurse<T>(withList : [T]) {
    if withList.isEmpty {
        return
    }
    var l = withList
    let t : T = l.popLast()!
    print(t)
    recurse(withList: l)
}

recurse(withList: static_ints)
recurse(withList: static_strs)

I'd rather do something like this:

func recurse<T>(withList : [T]) where withList.isEmpty {
  return
}

func recurse<T>(withList : [T]) {
    var l = withList
    let t : T = l.popLast()!
    print(t)
    recurse(withList: l)
}

recurse(withList: static_ints)
recurse(withList: static_strs)

Note the syntactic support for evaluating list state. Other accepted functional languages do this differently, but this would do the trick. So the most important thing with regard to functional support exists - tail recursion. The syntatic support, however, lags.

So how about the last two, type safety and constant assignment? Well, the language is not strongly typed, nor are the values idempotent. But they can be. Swift doesn't force you to use optional types after all. You can furthermore avoid the use of VAR, and use LET instead. But those things are not enforced by the language or runtime, as they are in more functional languages. And to be honest, runtime enforcement of these features would make integration with Objective-C and C more difficult.

So Swift has the key elements of functional languages, and you can safely program in a functional style in Swift. This is pretty rare for this kind of language - neither Java, or Python, or really any mainstream languages give you the environment to functionally program safely. But the features, for the most part, are not enforced by the language.

Overall? It's safe - if you want to, go ahead. But don't expect the language to help you do it.

Swift (programming language)

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Create a CLI Chatbot With the ChatGPT API and Node.js
  • Journey to Event Driven, Part 1: Why Event-First Programming Changes Everything
  • 5 Steps for Getting Started in Deep Learning
  • OpenVPN With Radius and Multi-Factor Authentication

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: