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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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
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

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Best Practices for Writing Clean and Maintainable Code
  • Misconceptions About No-Code Mobile App Testing
  • Scriptless Testing vs Scripted Testing: Which One Is for You?
  • 8 Metrics for Rapidly Scaling Dev Teams

Trending

  • Intro to RAG: Foundations of Retrieval Augmented Generation, Part 2
  • Implementing API Design First in .NET for Efficient Development, Testing, and CI/CD
  • How to Merge HTML Documents in Java
  • Understanding the Shift: Why Companies Are Migrating From MongoDB to Aerospike Database?
  1. DZone
  2. Coding
  3. Frameworks
  4. Four Ways to Quickly Test Swift Code

Four Ways to Quickly Test Swift Code

By 
Michael Crump user avatar
Michael Crump
·
May. 27, 15 · Interview
Likes (0)
Comment
Save
Tweet
Share
8.7K Views

Join the DZone community and get the full member experience.

Join For Free

As developers, we are always looking for a better, faster way of doing things. Whenever I am learning a new language that typically runs in an IDE, then I begin to look for ways to test code snippets through either the Terminal for Mac or the command prompt on Windows. Swift is no exception. As I’ve been working more and more with this language, I’ve uncovered four ways to quickly test Swift code that are not only great for your day-to-day job, but can be used to collaborate and help others learn this new language.

#1 : REPL (Read-Eval-Print-Loop)

Xcode’s debugger includes an interactive version of the Swift language, known as the REPL (Read-Eval-Print-Loop). This allows you to try out the Swift language within LLDB in Xcode’s console, or from Terminal.

If you have at least Xcode 6.1 or higher, then you can simply open your terminal and type:

swift

You can also invoke it with the following commands on earlier versions of Xcode 6 :

xcrun swift 
lldb --repl

It looks like the following:

replswift

This is great for quick code snippets that you might want to try without launching Xcode.

#2 : Swift playgrounds

Swift playgrounds are a way to compile and run Swift code live as you type. The results of each line are presented in a timeline as they execute, and variables can be inspected at any point. Playgrounds are typically created as a standalone project (as the image below indicates), but they can be created within an existing Xcode project as well.

xcodeplaygrounds

There are plenty of sample playgrounds out there, and you are free to usemine to get started. Below you will see an example of the timeline in action, providing a visual look of arrays, for loops and more.

demoplayground

The obvious reason to use Swift playgrounds is the rich editor that includes syntax highlighting, code completion and more. The disadvantage is that you have to open Xcode in order to do so.

#3 : Using an Online Editor

SwiftStub has become one of the most popular ways to compile and run Swift code on the fly without requiring a Mac. All you need is a web-browser open to SwiftStub and off you go.

swiftstub

It includes the functionality that you would expect, such as a custom URLs and uploading or saving a playground, but it also supports team collaboration.

swiftstubdemo

You can easily add people to your current Swift project and even add audio and group chat if neccessary.

#4 : Using iTerm2 with Guard-shell

This is my preferred environment, but it is geared towards power users that don’t mind spending a few extra minutes setting it up. Don’t worry if you have never done this before as I’ll walk you through the process, step-by-step.

I prefer to use iTerm2. Think of it as a replacement for the Terminal app on Mac. In the words of the authors, “iTerm2 brings the terminal into the modern age with features you never knew you always wanted.” I’ve been using it for a couple of months and couldn’t agree more.

We are also going to use the help of Guard-shell to automatically run shell commands when watched files are modified. In this case, we’ll be watching files with the .swift extention.

Once you have these applications downloaded, you only need to remember a few commands to get started…

Within iTerm2, press ⌘D to get a Vertical Split and ⇧⌘D for a horizontal split.

iterm2intro

Navigate to your home directory and type:

vim Guardfile

Once you are inside the Guardfile, you will need to switch to “Insert” mode. Simply type the following and when you are finished press “esc” and then type :w to save the file. Type :x to save and exit vim.

source 'https://rubygems.org'
gem 'guard-shell'

You will now have a file named Gemfile and it is time to install the gem.

Simply type:

bundle install

You should then see the following:

Fetching gem metadata from https://rubygems.org/............
Fetching version metadata from https://rubygems.org/..
Resolving dependencies...
Using hitimes 1.2.2
Using timers 4.0.1
Using celluloid 0.16.0
Installing coderay 1.1.0
Using ffi 1.9.8
Installing formatador 0.2.5
Using rb-fsevent 0.9.4
Using rb-inotify 0.9.5
Using listen 2.9.0
Installing lumberjack 1.0.9
Installing nenv 0.2.0
Installing shellany 0.0.1
Installing notiffany 0.0.6
Installing method_source 0.8.2
Installing slop 3.6.0
Installing pry 0.10.1
Installing thor 0.19.1
Installing guard 2.12.5
Installing guard-compat 1.2.1
Installing guard-shell 0.7.1
Using bundler 1.8.5
Bundle complete! 1 Gemfile dependency, 21 gems now installed.

Now would be a good time to create a directory where you want guard-shell to be monitoring for .swift files that have changed. I created a folder called Swift, then ran the following command :

bundle exec guard init shell

A new file called Guardfile will be created in that folder.

Now type vim Guardfile, enter the following lines and save the file the same way you did before.

guard :shell do
    watch(/(.*).swift/) do |m| 
        puts
        puts
        puts
        puts "Running #{m[0]}"
        puts `swift #{m[0]}`
    end
end

Finally type:

bundle exec guard

If everything worked successfully, then Guard-shell will inform you that it is watching a folder as shown below:

itermwithguard

Switch over to your left-hand panel and make sure you are in the folder that Guard is watching and type “vim test.swift” and type the following Swift code:

var first = "hello"
var second = "world"
println("\(first) \(second)")

Use :w to save the file and see the output in the right-hand panel as shown below.

guardcompileswift

Wrap-up

Hopefully you can find a solution that works for your development process out of the four options that I presented today. I assume that, since you are interested in testing Swift code snippets, you are building Swift apps as well. You may be interested in my article on how to build a task app in Swift as well. In addition, Telerik provides several powerful UI componentsfor iOS such as Charts, Calandar, ListView and more.

Thanks for reading and sound off in the comments below with your ideal environment.


Swift (programming language) code style Testing

Published at DZone with permission of Michael Crump. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Best Practices for Writing Clean and Maintainable Code
  • Misconceptions About No-Code Mobile App Testing
  • Scriptless Testing vs Scripted Testing: Which One Is for You?
  • 8 Metrics for Rapidly Scaling Dev Teams

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!