tag:computers.tutsplus.com,2005:/categories/swiftEnvato Tuts+ Computer Skills - Swift2017-07-24T08:52:05Ztag:computers.tutsplus.com,2005:PostPresenter/cms-29138Mobile Development Languages<p>If you want to code a mobile app, you need to know a programming language. But it can be hard to choose the best language (or languages) for a project. There are a lot of options out there, and in this post I'll help you narrow them down so that you can pick the best.</p><p>It all depends on what you're building. For certain apps, mobile developers may not need all the available features of a particular language. In other situations, a single app may require more than one language. In this tutorial, I'll go through various mobile development languages and highlight some of the details that can help you make a decision. </p><p>Let's start with some languages which you may already be familiar with.<br></p><h2>Android Languages<br>
</h2><h3>Java<br>
</h3><p>According to the <a href="https://www.tiobe.com/tiobe-index" rel="external" target="_blank">TIOBE</a> Index, Java is the most popular programming language as of June 2017. If you want to develop Android apps, you'll most likely to stick to Java. It has a large and established developer community, and that means you can easily get technical support and help. </p><p>So, when you're developing for mobile with Java, you are free to come up with any type of app you can think of. The only limits will be your imagination and the level of your Java knowledge.</p><ul class="roundup-block__contents posts--half-width roundup-block--list">
<li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/articles/android-from-scratch-an-overview-of-android-application-development--cms-25972"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/362/posts/25972/preview_image/picGeneric.jpg"><div class="roundup-block__primary-category topic-code">Android</div>
<div class="roundup-block__content-title">Android From Scratch: An Overview of Android Application Development</div>
<div class="roundup-block__author">Ashraff Hathibelagal</div></a></li>
<li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/courses/learn-java-for-android"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/71/courses/694/preview_image/java-android-1.png"><div class="roundup-block__primary-category topic-code">Java</div>
<div class="roundup-block__content-title">Learn Java for Android</div>
<div class="roundup-block__author">Sue Smith</div></a></li>
</ul><h3>Kotlin</h3><p>Kotlin was designed and developed by JetBrains, the Czech company known for their popular IDE, IntelliJ IDEA. Google's Android team has recently announced that they are officially adding support for the Kotlin programming language. </p><p>Kotlin was developed to address some of the issues in Java. According to the language's fans, Kotlin syntax is simpler, cleaner, and leads to less code bloat. This helps you focus more on solving the actual problem, rather than struggling with verbose syntax. Also, you can use Kotlin and Java together in the same project, and that makes it really powerful.</p><ul class="roundup-block__contents posts--half-width roundup-block--list"><li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/articles/java-vs-kotlin-should-you-be-using-kotlin-for-android-development--cms-27846"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/369/posts/27846/preview_image/java-or-kotlin-for-android-dev.jpg"><div class="roundup-block__primary-category topic-code">Android SDK</div>
<div class="roundup-block__content-title">Java vs. Kotlin: Should You Be Using Kotlin for Android Development?</div>
<div class="roundup-block__author">Jessica Thornsby</div></a></li></ul><h2>iOS Languages</h2><h3>Swift<br>
</h3><p>If you want to develop for iOS, Swift might be the language for you. Introduced in 2014 and declared open source in 2015, Swift is swiftly catching up with mobile developers. It's very popular, especially among new iOS development startups. </p><p>Apple has added some great features to the language, such as simplified syntax, the ability to easily pinpoint programmer errors, etc. Apple's huge efforts to promote Swift clearly indicate that it wants this new language to become the mainstream programming language for its app ecosystem.</p><ul class="roundup-block__contents posts--half-width roundup-block--list">
<li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/courses/create-ios-apps-with-swift-3"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/71/courses/969/preview_image/swift-2.png"><div class="roundup-block__primary-category topic-code">Swift</div>
<div class="roundup-block__content-title">Create iOS Apps With Swift</div>
<div class="roundup-block__author">Markus Mühlberger</div></a></li>
<li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/tutorials/swift-from-scratch-introduction--cms-22598"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/41/posts/22598/preview_image/preview_image@2x.jpg"><div class="roundup-block__primary-category topic-code">Swift</div>
<div class="roundup-block__content-title">Swift From Scratch: Introduction</div>
<div class="roundup-block__author">Bart Jacobs</div></a></li>
</ul><h3>Objective-C<br>
</h3><p>Objective-C was the original development language for iOS. While the recently introduced Swift language is the future of iOS development, many advanced projects still rely on Objective-C. So the transition from Objective-C to Swift is expected to be somewhat slow, and you may need both of them for some projects, at least for the time being.</p><h2>Cross-Platform Languages</h2><h3>JavaScript<br>
</h3><p>JavaScript has a long history going back to the early days of the World Wide Web. A very popular front-end and server-side language, it lets web developers do everything from enhancing the user experience of their websites to building complete web apps. </p><p>Today, there are several JavaScript frameworks that specifically target mobile development platforms, such as Ionic 2 and React Native. It's very easy to develop cross-platform mobile apps using these frameworks and libraries. This means you only have to write a single version of your app, and it will run on iOS or Android.</p><ul class="roundup-block__contents posts--half-width roundup-block--list">
<li class="roundup-block__content free-course">
<div class="free-course__label">FREE</div>
<a class="roundup-block__content-link" href="https://code.tutsplus.com/courses/javascript-fundamentals"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/71/courses/544/preview_image/js400.jpg"><div class="roundup-block__primary-category topic-code">JavaScript</div>
<div class="roundup-block__content-title">Modern JavaScript Fundamentals</div>
<div class="roundup-block__author">Dan Wellman</div></a>
</li>
<li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/articles/introduction-to-ionic-2--cms-28193"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/1125/posts/28193/preview_image/ionic.png"><div class="roundup-block__primary-category topic-code">Ionic 2</div>
<div class="roundup-block__content-title">Introduction to Ionic 2</div>
<div class="roundup-block__author">Wern Ancheta</div></a></li>
<li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/courses/get-started-with-react-native"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/16/courses/708/preview_image/react-1.png"><div class="roundup-block__primary-category topic-code">React Native</div>
<div class="roundup-block__content-title">Get Started With React Native</div>
<div class="roundup-block__author">Markus Mühlberger</div></a></li>
</ul><h3>TypeScript</h3><p>TypeScript is a superset of JavaScript and offers better safety by adding optional static typing. It also provides better support for developing large-scale applications. Developed and maintained by Microsoft, TypeScript allows developers to write cross-platform mobile apps using frameworks such as NativeScript.</p><ul class="roundup-block__contents posts--half-width roundup-block--list">
<li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/tutorials/getting-started-with-typescript--net-28890"><img class="roundup-block__preview-image" data-src="https://cdn.tutsplus.com/net/authors/jeffreyway/getting-started-with-typescript.png"><div class="roundup-block__primary-category topic-code">Web Development</div>
<div class="roundup-block__content-title">Getting Started with TypeScript</div>
<div class="roundup-block__author">Sayanee Basu</div></a></li>
<li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/courses/code-a-mobile-app-with-nativescript"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/71/courses/1050/preview_image/ns-1.png"><div class="roundup-block__primary-category topic-code">NativeScript</div>
<div class="roundup-block__content-title">Code a Mobile App With NativeScript</div>
<div class="roundup-block__author">Keyvan Kasaei</div></a></li>
</ul><h2>Other Languages</h2><h3>
<strong></strong>C#<br>
</h3><p>C# is the language of Windows Mobile. It's very similar to C++ and Java. Microsoft has adopted some of the features of Java to simplify its architecture, while maintaining the C++ like design. It also has a large and active community of developers who are always friendly and helpful.</p><h3>C<br>
</h3><p>C is the second most popular language on the TIOBE index, and just like Java, its community is full of seasoned developers who could offer you valuable advice on how to write bug-free code. </p><p>Created by Dennis Ritchie, while working for Bell Labs, C is a widely adopted and powerful language that allows you to directly manipulate low-level operations of a computer. If you want to use Android NDK (Native Development Kit), you'll need to get familiar with the C language.</p><h3>C++<br>
</h3><p>If you are familiar with C, then you'll really enjoy reading and writing C++ code. C++ is an extension of C, with more high-level features and support for object-oriented programming. C++ is also a favorite language of Android NDK developers. You can use C++ to develop Windows Mobile apps too. C++ goes head to head with Java in the field of software development, and it's really worth mastering.<br></p><h3>Python<br>
</h3><p>Python is another popular language that's easy to learn and easy to read. The creators of the language have made extra efforts to keep the syntax as simple and clear as possible. This really helps novice developers maintain high levels of productivity, from day one. If you are comfortable with writing Python code, then you can use frameworks such as Kivy to develop cross-platform mobile apps.</p><ul class="roundup-block__contents posts--half-width roundup-block--list"><li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/courses/introduction-to-python"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/71/courses/647/preview_image/intro-python-1.png"><div class="roundup-block__primary-category topic-code">Python</div>
<div class="roundup-block__content-title">Learn to Code With Python</div>
<div class="roundup-block__author">Derek Jensen</div></a></li></ul><h3>Ruby<br>
</h3><p>Ruby is an object-oriented scripting language, influenced by Ada, C++, Perl, Python, and Lisp. RubyMotion is a great framework for developing native and cross-platform mobile apps in Ruby. It's fairly easy to learn Ruby, thanks to its elegant syntax that focuses on simplicity and productivity.</p><ul class="roundup-block__contents posts--half-width roundup-block--list"><li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/courses/learn-to-code-with-ruby"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/71/courses/558/preview_image/ruby_writing.png"><div class="roundup-block__primary-category topic-code">Programming Fundamentals</div>
<div class="roundup-block__content-title">Learn to Code With Ruby</div>
<div class="roundup-block__author">José Mota</div></a></li></ul><h2>How to Classify the Languages?<br>
</h2><p>Mobile apps can be grouped into three categories, namely native, hybrid, and native cross-platform. Native apps can fully utilize all the OS facilities and features, and they are the fastest when it comes to performance. However, you need to maintain different codebases for different mobile platforms, as each platform uses different programming languages.<br></p><p>For example, Android platform makes use of Java plus C/C++ to develop native apps. Apple's iOS platform relies on Objective-C and Swift as its native languages. C# is used by Windows Mobile platform to code its native apps. All of these native app programming languages are compiled, rather than interpreted.</p><p>Hybrid mobile apps are actually websites that are designed to work with mobile devices too. A user can access them via a mobile browser as if they are visiting a website on a desktop computer. The combination of HTML5, CSS and JavaScript is the obvious choice, if you want to develop web apps.<br></p><p>Recently, a new batch of mobile cross-platform frameworks has emerged. These frameworks combine the best features of native apps and hybrid apps—they're fast and light and can access the full power of the native device, but they also are coded with JavaScript and other web languages, so a lot of code can be reused between platforms.</p><p>React Native and NativeScript are popular native cross-platform frameworks. If you want to learn more about these, check out our comprehensive beginner course or some of our many tutorials.</p><h2>Comparison of Features<br>
</h2><p>Before getting deeper into the detailed language features, you must select a platform. You can refer to the article <a href="https://code.tutsplus.com/articles/mobile-development-platforms--cms-28944" target="_self">Mobile Development Platforms</a> to get an idea of various platforms and how to pick the one that suits you best. Assuming that you've already selected a mobile development platform, let's see how these languages compare in terms of their features.<br></p><ul class="roundup-block__contents posts--half-width roundup-block--list"><li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/articles/mobile-development-platforms--cms-28944"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/769/posts/28944/preview_image/mobile%20devices.jpg"><div class="roundup-block__primary-category topic-code">Mobile Development</div>
<div class="roundup-block__content-title">Mobile Development Platforms</div>
<div class="roundup-block__author">Sandamal Siripathi</div></a></li></ul><h3>Native Android<br>
</h3><p>If you want to develop for native Android, Java and Kotlin are your obvious choices. So let's have a look at them.</p><h4>Null Safety</h4><p>Kotlin has better control over Null references so that the famous <code class="inline">NullPointerException</code> bugs (common in Java) are much easier to eliminate. This reduces development time and improves programmer productivity.</p><h4>Concurrency</h4><p>Although Java supports concurrent operations, the relevant code may suffer heavily from readability and maintainability issues. Kotlin addresses these issues by using Coroutines. The resulting code is easily readable and easily understandable too.</p><h4>Type System</h4><p>Java's type system isn't consistent, and this can sometimes lead to confusion. In particular, the primitive types such as integer, boolean, and so on need to be handled as special cases. By contrast, Kotlin has a relatively simple and more versatile type system that minimizes programmer errors and mistakes.</p><h4>Supported Programming Styles</h4><p>Although Java can theoretically support various programming styles, some developers believe that it overly promotes OOP (Object-Oriented Programming). Kotlin doesn't seem to enforce any particular style of programming, so developers have more freedom to choose an approach that fits best. However, Kotlin developers need to have a thorough knowledge of software architecture and development principles.</p><h4>Which One to Choose?</h4><p>In a nutshell, it seems that Kotlin is better than Java, but it may take some time for a complete transformation. One challenge is that programmers are used to the thinking patterns enforced by Java. Another is that Kotlin is a new language, and certain features are still experimental.</p><p>Anyway, Google has clearly announced that they will offer complete support for Kotlin. In fact, Android Studio, the official Android IDE, now comes with full support for Kotlin. New features and capabilities are constantly added to Kotlin. Over the next few years, we are going to experience a transition period from Java to Kotlin, at least in native Android development.</p><h3>Native iOS</h3><p>Objective-C and Swift are the two options you have for iOS development. So let's have a look at each one's features.</p><h4>Code Syntax</h4><p>Swift has simpler and clearer syntax to help programmers achieve their goals with the minimum number of LOC (Lines Of Code). This also helps reduce programmer errors and eases bug fixing.</p><h4>Memory Management</h4><p>Swift clearly beats Objective-C, when it comes to memory management. Swift enforces more robust and reliable control mechanisms, allowing programmers to avoid undesirable memory leaks.</p><h4>Performance</h4><p>Execution of Swift code is much faster than that of Objective-C. This clearly leads to faster app performance and better user experience.</p><h4>Supported Programming Styles</h4><p>Unlike Objective-C, Swift has built-in support for functional programming too. So developers don't have to limit themselves to any pre-defined programming styles. That helps developers understand the problem clearly and come up with a better solution.</p><h4>Which One to Choose?</h4><p>Just as Kotlin is slowly replacing Java in native Android development, Swift seems sure to thrive in native iOS development, forcing Objective-C to retire. Apple has already started extensive support for Swift, and that's going to get even better in the future. Like Android developers, iOS developers are also experiencing a transition period at the moment. </p><p>While there are several code migration tools available, it may not be possible to fully convert Objective-C projects to Swift without issues. Sometimes, specific workarounds may be required, and that might need a fair knowledge of Objective-C. So the best strategy is to give priority to Swift and learn a bit of Objective-C only when it's absolutely necessary. Also, you need to keep an eye on the latest Swift developments and trends.</p><h3>Cross-Platform Apps<br>
</h3><p>JavaScript (coupled with other HTML5 technologies) is the most used cross-platform mobile development language. There are also other languages, such as Python and Ruby, but JavaScript has the broadest range of support and adoption. </p><p>Unless you are already a big Ruby or Python fan and you want to try out the cutting-edge of mobile development with those languages, you should stick with JavaScript or its type-augmented sibling, TypeScript.</p><h2>Conclusion<br>
</h2><p>Choosing a mobile development language can be tricky if you don't understand the features of each one, along with the current industry trends. With this knowledge, though, it's easy to see that choosing a language heavily depends on the particular mobile development platform too.</p><p>I'm sure now you have a clearer picture of mobile app development languages and are able to match the relevance of their features to the latest development trends. So just get started coding your next app with confidence!</p><p>If you want some help getting started with a new language, check out some of the tutorials and video courses linked throughout this post, or some of our other posts on mobile development!</p><ul class="roundup-block__contents posts--half-width roundup-block--list">
<li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/articles/mobile-development-platforms--cms-28944"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/769/posts/28944/preview_image/mobile%20devices.jpg"><div class="roundup-block__primary-category topic-code">Mobile Development</div>
<div class="roundup-block__content-title">Mobile Development Platforms</div>
<div class="roundup-block__author">Sandamal Siripathi</div></a></li>
<li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/tutorials/get-started-with-layouts-in-react-native--cms-27418"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/1125/posts/27418/preview_image/rn.jpg"><div class="roundup-block__primary-category topic-code">React Native</div>
<div class="roundup-block__content-title">Get Started With React Native Layouts</div>
<div class="roundup-block__author">Wern Ancheta</div></a></li>
<li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/tutorials/create-your-first-nativescript-app--cms-26957"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/1125/posts/26957/preview_image/ns.jpg"><div class="roundup-block__primary-category topic-code">NativeScript</div>
<div class="roundup-block__content-title">Create Your First NativeScript App</div>
<div class="roundup-block__author">Wern Ancheta</div></a></li>
<li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/tutorials/start-developing-android-apps-with-kotlin-part-1--cms-27827"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/369/posts/27827/preview_image/start-developing-android-apps-with-kotlin.jpg"><div class="roundup-block__primary-category topic-code">Android Studio</div>
<div class="roundup-block__content-title">Coding Functional Android Apps in Kotlin: Getting Started</div>
<div class="roundup-block__author">Jessica Thornsby</div></a></li>
<li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/tutorials/swift-from-scratch-an-introduction-to-functions--cms-22879"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/41/posts/22879/preview_image/preview_image@2x.jpg"><div class="roundup-block__primary-category topic-code">Swift</div>
<div class="roundup-block__content-title">Swift From Scratch: An Introduction to Functions</div>
<div class="roundup-block__author">Bart Jacobs</div></a></li>
<li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/tutorials/whats-the-difference-between-java-and-javascript--cms-26194"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/34/posts/26194/preview_image/javascript.png"><div class="roundup-block__primary-category topic-code">Java</div>
<div class="roundup-block__content-title">What's the Difference Between Java and JavaScript?</div>
<div class="roundup-block__author">Tom McFarlin</div></a></li>
<li class="roundup-block__content"><a class="roundup-block__content-link" href="https://code.tutsplus.com/tutorials/code-your-first-ionic-2-app-photo-sharing-app--cms-28469"><img class="roundup-block__preview-image" data-src="https://cms-assets.tutsplus.com/uploads/users/1125/posts/28469/preview_image/ionic.png"><div class="roundup-block__primary-category topic-code">Ionic 2</div>
<div class="roundup-block__content-title">Code Your First Ionic 2 App: Getting Set Up</div>
<div class="roundup-block__author">Wern Ancheta</div></a></li>
</ul><p></p>2017-07-24T08:52:05.341Z2017-07-24T08:52:05.341ZSandamal Siripathitag:computers.tutsplus.com,2005:PostPresenter/cms-21807Alfred Workflows in Swift<p>Apple created a new language to supplement <i>Objective-C</i>: <b>Swift</b>. <b>Swift</b> is still in the C language class, but has some features of an interpreted language. The simpler syntax compared to <i>Objective-C </i>will make learning and using it much easier. <b>Swift</b> is usable as an interpreter or a compiler.<br></p><p>I’m introducing this language by showing how to use it with Alfred Workflows and I assume that you're already familiar with writing workflows in Alfred. If not, please check out these tutorials: <b>Alfred</b> for <a href="https://computers.tutsplus.com/tutorials/alfred-workflows-for-beginners--mac-55446"><i>Beginners</i></a><i>, </i><a href="https://computers.tutsplus.com/tutorials/alfred-workflows-for-intermediates--mac-60557"><i>Intermediates</i></a><i>, </i><a href="https://computers.tutsplus.com/tutorials/alfred-workflows-for-advanced--mac-60963"><i>Advanced</i></a><i>,</i> and <a href="https://computers.tutsplus.com/tutorials/alfred-debugging--cms-20439"><i>Alfred Debugging</i></a>.</p>
<p>This tutorial focuses on using <b>Swift</b> with <b>Alfred</b> and not a complete language reference. There is a great tutorial series about learning <b>Swift</b> on Code Tuts+, <a href="https://code.tutsplus.com/tutorials/an-introduction-to-swift-part-1--cms-21389"><i>An Introduction to Swift: Part 1</i></a> and <a href="https://code.tutsplus.com/tutorials/an-introduction-to-swift-part-2--cms-21484"><i>An Introduction to Swift: Part 2</i></a>. I will assume that you have read these articles already.</p>
<h2>Installing Xcode 6.1</h2>
<p>To install <strong>Swift</strong> on a Mac, you have to install XCode from the App Store. Once installed, you need to open a terminal window and run:</p>
<p><code class="inline">xcode-select -s /Applications/Xcode.app/ --install</code></p>
<p>That will make all the XCode tools available to the command line.</p>
<h2>Adding Swift to the Shell</h2>
<p>You can compile and experiment with <strong>Swift</strong> in <b>XCode 6.1</b> and it’s <strong>Playground</strong>. This tutorial focuses on using <strong>Swift</strong> on the command line using only a programmer’s editor and the command line.</p>
<p>Assuming you installed <b>XCode 6.1</b> to the <b>Applications</b> folder, you will need to add <strong>Swift</strong>’s executables directory to the path. For <strong>Bash</strong>, add this to your <strong>~/.bashrc</strong> file:</p>
<pre class="brush: bash noskimlinks noskimwords">export PATH="$PATH:/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin"
</pre>
<p>For <strong>Zsh</strong>, add the same line to your <strong>~/.zshrc</strong> file. For <strong>Fish</strong> shell, add this line:</p>
<pre class="brush: bash noskimlinks noskimwords">set -xg PATH "/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin" $PATH
</pre>
<p>I have found that using the <strong>xcrun</strong> command without having the PATH set as above does not always work.</p>
<p>To compile <strong>Swift</strong> files on the command line, you type:</p>
<pre class="brush: bash noskimlinks noskimwords">swiftc &lt;swift file&gt;</pre>
<p>To run <strong>Swift</strong> in an interactive interpreter, you type:</p>
<pre class="brush: bash noskimlinks noskimwords">swift</pre>
<h2>Adding Swift to an Editor</h2>
<p>Adding <strong>Swift</strong> support for <strong>Sublime Text</strong> is easy. Install <a href="https://sublime.wbond.net/installation">Package Manager for Sublime Text</a>. Once you have Package Manager, you need to install the package <strong>Swift</strong> by using <strong>Shift-Command-P</strong>, type <strong>package install</strong>, <b>enter</b>, and <strong>Swift</strong>. This should install the <strong>Swift</strong> package.</p>
<p>On <strong>Emacs</strong>, the package manager for <strong>Emacs</strong> is the best route, but it is only in <strong>Emacs 24+</strong>. For <strong>Emacs 24+</strong>, you need to download and install <a href="http://aquamacs.org/"><strong>Aquamacs</strong></a>. The <strong>Emacs</strong> installed on a standard Mac is version 22. To install <strong>Aquamacs</strong> using <a href="http://brew.sh/"><strong>HomeBrew</strong></a> and <a href="https://github.com/caskroom/homebrew-cask"><strong>HomeBrew Cask</strong></a>, type this in a terminal:</p>
<pre class="brush: bash noskimlinks noskimwords">brew cask install aquamacs
</pre>
<p>Once installed, you have to add this to your <em>~/.emacs</em> file:</p>
<pre class="brush: bash noskimlinks noskimwords">(require 'package)
(package-initialize)
(add-to-list 'package-archives '("melpa" . "http://melpa.milkbox.net/packages/"))
</pre>
<p>Run <strong>Aquamacs</strong> and open the <em>Emacs Package Manager</em> with <strong>Meta-x package-list-packages</strong>.</p>
<figure class="post_image">
<img data-src="https://cms-assets.tutsplus.com/uploads/users/71/posts/21807/image/AlfredWorkflowSwift-01.jpg" alt="Emacs Package Manager">
<figcaption>Emacs Package Manager</figcaption></figure>
<p>Look for <strong>swift-mode</strong> and click it. You might need to install <strong>flycheck</strong> as well.</p>
<p>For <strong>Vim</strong>, you need to install <a href="https://github.com/Keithbsmiley/swift.vim"><strong>Swift.Vim</strong></a>. The easiest way to install <strong>Swift.Vim</strong> is to install <a href="https://github.com/square/maximum-awesome"><strong>maximum-awesome</strong></a> first. To install <strong>maximum-awesome</strong>, open a terminal in to the <strong>~/Documents</strong> (or any other directory. It has to be some where you plan to keep.). Type the following:</p>
<pre class="brush: bash noskimlinks noskimwords">git clone https://github.com/square/maximum-awesome.git
cd maximum-awesome
rake
</pre>
<p>The install will take a while. Afterwards, add this line to your <strong>~/.vimrc.bundle.local</strong> file:</p>
<pre class="brush: bash noskimlinks noskimwords">Plugin 'Keithbsmiley/swift.vim'
</pre>
<p>Once saved, rerun <strong>Vim</strong> and type</p>
<pre class="brush: bash noskimlinks noskimwords">:PluginInsall</pre><p><strong><a href="https://github.com/gmarik/Vundle.vim">Vundle</a></strong>, which <strong>maximum-awesome</strong> installs, will install any new plugins.</p>
<figure class="post_image">
<img data-src="https://cms-assets.tutsplus.com/uploads/users/71/posts/21807/image/AlfredWorkflowSwift-02.jpg" alt="Vundler Installing SwiftVim">
<figcaption>Vundler Installing Swift.Vim</figcaption></figure>
<p>In this case, <strong>Vundler</strong> installs the <strong>Swift.Vim</strong> plugin. <strong>Vim</strong> will now do syntax highlighting for <strong>Swift</strong>.</p>
<h2>Swift Interpreted vs Compiled</h2><p><strong>Swift</strong> can run as an interpreter or a compiler. To illustrate that, create a file <strong>hello.swift</strong> and add this to it:</p>
<pre class="brush: bash noskimlinks noskimwords">#!/usr/bin/env xcrun -sdk macosx swift
println("Hello World!")
</pre>
<p>This is the most basic <em>hello world</em> program that people use as their first program. The first line tells the shell you want to run this script using <strong>xcrun</strong> with the command line specified. <strong>xcrun</strong> is a Mac OSX program for running XCode utilities from the command line.</p>
<p>Save the file and change it’s execution mode with</p>
<pre class="brush: bash noskimlinks noskimwords">chmod x+a hello.swift
</pre>
<p>Run the file with</p>
<pre class="brush: bash noskimlinks noskimwords">./hello.swift
</pre>
<p>And it will produce <strong>Hello World!</strong> on the terminal by running the script with <strong>Swift</strong> as an interpreter. To compile, type this on the terminal:</p>
<pre class="brush: bash noskimlinks noskimwords">swiftc hello.swift
</pre>
<p>A <strong>hello</strong> program now exists in that directory. Type</p>
<pre class="brush: bash noskimlinks noskimwords">./hello
</pre>
<p>and you will see the exact same output.</p>
<figure class="post_image">
<img data-src="https://cms-assets.tutsplus.com/uploads/users/71/posts/21807/image/AlfredWorkflowSwift-03.jpg" alt="Hello World Program">
<figcaption>Hello World Program</figcaption></figure>
<p>Both methods produced the exact same result. The only thing different is that for the interpreted approach, <strong>XCode 6</strong> has to be on every system that runs it. If you compile the program, it can be ran on any Mac.</p>
<p>An interesting note about the interpreted approach is that it is the same as the compiled approach for what gets ran. In interpreted mode, it compiles the program in memory and runs directly in memory. The compiled approach compiles to disk and you run the program. Overall, you do not save any time by interpreting Swift code.</p>
<h2>Alfred Library</h2>
<p>To make writing programs for use in <strong>Alfred</strong>, a library of helper functions can be a great asset. Create a new file called <strong>Alfred.swift</strong> and place this code inside:</p>
<pre class="brush: objc noskimlinks noskimwords">//
// Class: Alfred
//
// Description: This class if for helping in creating workflows for Alfred using
// Apple's Swift language.
//
// Class Variables:
//
// Name Description
//
// cache path to the directory that contains the cache for the workflow
// data path to the directory that contains the data for the workflow
// bundleId The ID for the bundle that represents the workflow
// path path to the workflow's directory
// home path to the user's home directory
// results the accumulated results. This will be converted to the XML list for
// feedback into Alfred
//
//
// Import Libraries that are needed.
//
import Foundation
//
// Define structures used.
//
struct AlfredResult {
var Uid: String = ""
var Arg: String = ""
var Title: String = ""
var Sub: String = ""
var Icon: String = ""
var Valid: String = ""
var Auto: String = ""
var Rtype: String = ""
}
//
// Class: Regex
//
// Description: This is a helper class for writing tests using regular expressions. Based
// on article: http://benscheirman.com/2014/06/regex-in-swift/
//
class Regex {
let internalExpression: NSRegularExpression
let pattern: String
init(_ pattern: String) {
self.pattern = pattern
var error: NSError?
self.internalExpression = NSRegularExpression(pattern: pattern, options: .CaseInsensitive, error: &amp;error)!
}
func test(input: String) -&gt; Bool {
let matches = self.internalExpression.matchesInString(input, options: nil, range:NSMakeRange(0, count(input)))
return matches.count &gt; 0
}
}
//
// Class: Alfred
//
// Description: This class encloses the functions needed to write workflows for Alfred.
//
public class Alfred {
var cache: String = ""
var data: String = ""
var bundleId: String = ""
var path: String = ""
var home: String = ""
var fileMGR: NSFileManager = NSFileManager()
var maxResults: Int = 10
var currentResult: Int = 0
var results: [AlfredResult] = []
//
// Library class Function:
//
// init This class function is called upon library use to initialize
// any variables used for the library before anyone
// can make a call to a library class function.
//
public init() {
//
// Create the result array.
//
var resfirst:AlfredResult = AlfredResult()
resfirst.Title = "No matches found..."
resfirst.Uid = "default"
resfirst.Valid = "no"
resfirst.Arg = ""
resfirst.Sub = ""
resfirst.Icon = ""
resfirst.Auto = ""
resfirst.Rtype = ""
results.append(resfirst)
maxResults = 10
currentResult = 0
//
// Set the path and home variables from the environment.
// in Objective C: NSString* path = [[[NSProcessInfo processInfo]environment]objectForKey:@"PATH"];
//
let process = NSProcessInfo.processInfo();
let edict = NSDictionary(dictionary: process.environment)
path = fileMGR.currentDirectoryPath
home = edict["HOME"] as! String
//
// If the info.plist file exists, read it for the bundleid and set the bundleId variable.
//
bundleId = GetBundleId()
//
// Create the directory structure for the cache and data directories.
//
cache = home + "/Library/Caches/com.runningwithcrayons.Alfred-2/Workflow Data/" + bundleId;
data = home + "/Library/Application Support/Alfred 2/Workflow Data/" + bundleId;
//
// See if the cache directory exists.
//
if(!fileMGR.fileExistsAtPath(cache)) {
//
// It does not exist. Create it!
//
fileMGR.createDirectoryAtPath(cache, withIntermediateDirectories:true, attributes:nil, error:nil)
}
//
// See if the data directory exists.
//
if(!fileMGR.fileExistsAtPath(data)) {
//
// It does not exist. Create it!
//
fileMGR.createDirectoryAtPath(data, withIntermediateDirectories:true, attributes:nil, error:nil)
}
}
//
// class Function: GetBundleId
//
// Description: This class function will read the workflows info.plist and return
// the bundleid
//
public func GetBundleId() -&gt; String {
//
// get the bundle ID from the plist if already not retrieved.
//
if( bundleId == "" ) {
let path = NSBundle.mainBundle().pathForResource("info", ofType: "plist")
let dict = NSDictionary(contentsOfFile: path!)!
bundleId = dict["bundleid"] as! String
}
//
// Return the bundle ID.
//
return(bundleId)
}
//
// class Function: Cache
//
// Description: This class function returns the cache directory for the workflow.
//
public func Cache() -&gt; String {
return( cache )
}
//
// class Function: Data
//
// Description: This class function returns the data directory for the workflow.
//
public func Data() -&gt; String {
return( data )
}
//
// class Function: Path
//
// Description: This class function returns the path to the workflow.
//
public func Path() -&gt; String {
return( path )
}
//
// class Function: Home
//
// Description: This class function returns the Home directory for the user.
//
public func Home() -&gt; String {
return( home )
}
//
// class Function: ToXML
//
// Description: This class function takes the result array and makes it into an
// XML String for passing back to Alfred.
//
public func ToXML() -&gt; String {
var newxml: String = "&lt;items&gt;"
for result in results {
newxml += "&lt;item uidid='\(result.Uid)' valid='\(result.Valid)' autocomplete='\(result.Auto)' type='\(result.Rtype)'&gt;&lt;arg&gt;\(result.Arg)&lt;/arg&gt;&lt;title&gt;\(result.Title)&lt;/title&gt;&lt;sub&gt;\(result.Sub)&lt;/sub&gt;&lt;icon&gt;\(result.Icon)&lt;/icon&gt;&lt;/item&gt;"
}
//
// Close the xml and return the XML String.
//
newxml += "&lt;/items&gt;"
return(newxml)
}
//
// class Function: AddResult
//
// Description: Helper class function that just makes it easier to pass values
// into a class function
// and create an array result to be passed back to Alfred.
//
// Inputs:
// uid the uid of the result, should be unique
// arg the argument that will be passed on
// title The title of the result item
// sub The subtitle text for the result item
// icon the icon to use for the result item
// valid sets whether the result item can be actioned
// auto the autocomplete value for the result item
// rtype I have no idea what this one is used for. HELP!
//
public func AddResult( uid: String, arg: String, title: String, sub: String, icon: String, valid: String, auto: String, rtype: String) {
//
// Add in the new result array if not full.
//
if (currentResult &lt; maxResults) {
if(currentResult != 0) {
var resfirst:AlfredResult = AlfredResult()
resfirst.Title = title
resfirst.Uid = uid
resfirst.Valid = valid
resfirst.Arg = arg
resfirst.Sub = sub
resfirst.Icon = icon
resfirst.Auto = auto
resfirst.Rtype = rtype
results.append(resfirst)
} else {
results[0].Title = title
results[0].Uid = uid
results[0].Valid = valid
results[0].Arg = arg
results[0].Sub = sub
results[0].Icon = icon
results[0].Auto = auto
results[0].Rtype = rtype
}
currentResult++
}
}
//
// class Function: AddResultsSimilar
//
// Description: This class function will only add the results that are similar to the
// input given. This is used to select input selectively from what the
// user types in.
//
// Inputs:
// inString the String to test against the titles to allow that record or not
// uid the uid of the result, should be unique
// arg the argument that will be passed on
// title The title of the result item
// sub The subtitle text for the result item
// icon the icon to use for the result item
// valid sets whether the result item can be actioned
// auto the autocomplete value for the result item
// rtype I have no idea what this one is used for. HELP!
//
public func AddResultsSimilar(uid: String, inString: String, arg: String, title: String, sub: String, icon: String, valid: String, auto: String, rtype: String) {
//
// Create the test pattern.
//
var matchstr = inString + ".*"
//
// Compare the match String to the title for the Alfred output.
//
if(Regex(inString + ".*").test(title)) {
//
// A match, add it to the results.
//
AddResult( uid, arg: arg, title: title, sub: sub, icon: icon, valid: valid, auto: auto, rtype: rtype)
}
}
//
// class Function: SetDefaultString
//
// Description: This class function sets a different default title
//
// Inputs:
// title the title to use
//
public func SetDefaultString(title: String) {
if(currentResult == 0) {
//
// Add only if no results have been added.
//
results[0].Title = title
}
}
}
</pre>
<p>This is a port of my <a href="https://github.com/raguay/goAlfred">Alfred go language library</a> that I use in the tutorial <a href="https://computers.tutsplus.com/tutorials/track-project-time-with-alfred-timekeeper--cms-20981">Track Project Time With Alfred Timekeeper</a> to <strong>Swift</strong>. I define one structure, <code class="inline">AlfredResult</code>, to keep items to return to a <strong>Script Filter</strong> in <strong>Alfred</strong>, a class for using the <code class="inline">NSRegularExpression</code> <strong>Objective-C</strong> class, and the <em>Alfred</em> class for handling everything that an <strong>Alfred</strong> workflow would need.</p>
<p>At this point, you noticed that I mentioned an <strong>Objective-C</strong> class. <strong>Swift</strong> does not remove the need to use <strong>Objective-C</strong> libraries. The <strong>Swift</strong> standard library has basic language constructs and routines. Nothing that is operating system specific. All <strong>Objective-C</strong> libraries are usable directly from <strong>Swift</strong>. So, don’t throw out all your <strong>Objective-C</strong> reference manuals. They’re still needed.</p>
<p>The <strong>Alfred</strong> class has an initialization routine that obtains the different directory paths a workflow would use and create the data and cache directories if they do not already exist. The methods <code>AddResult()</code> and <code>AddResultsSimilar()</code> create the results structure for the XML outputs to <strong>Alfred</strong>. The <code>AddResultsSimilar()</code> only adds the result if it was similar to the title line. The <code>ToXML()</code> function outputs the XML of the results array.</p>
<h2>The Workflow</h2>
<p>The example workflow will be a case converter. I created it once in PHP, but for many systems it runs real slow. It will take a string on the <strong>Alfred</strong> prompt, or from the OSX selection using a hotkey, and give a list of available conversions. It shows the resulting conversion as you type. The conversion the user selects is the one sent to the clipboard and the top application.</p>
<figure class="post_image">
<img data-src="https://cms-assets.tutsplus.com/uploads/users/71/posts/21807/image/AlfredWorkflowSwift-04.jpg" alt="Alfred Case Converter Workflow">
<figcaption>Alfred Case Converter Workflow</figcaption></figure>
<p>Create an Alfred workflow as you see above.</p>
<figure class="post_image">
<img data-src="https://cms-assets.tutsplus.com/uploads/users/71/posts/21807/image/AlfredWorkflowSwift-05.jpg" alt="Workflows Script Filter">
<figcaption>Workflow’s Script Filter</figcaption></figure>
<p>Set the <strong>ScriptFilter</strong> as you see above. Select the <strong>Open workflow folder</strong> at the bottom right corner. A <strong>Finder</strong> window will open to the directory for the workflow. Copy the <strong>Alfred library</strong> file created earlier to this directory. Then create a new file called <strong>tcconverter.swift</strong> and add this code to the bottom of the file:</p>
<pre class="brush: objc noskimlinks noskimwords">//
// Program: Text Case Converter (tcconverter)
//
// Description: This program will take a string on the command line, convert
// it in several ways, and create a xml output for showing
// in an Alfred Script Filter.
//
//
// Import Libraries:
//
import Alfred
import Foundation
class Converter {
init() {
//
// Create the Alfred object.
//
var wf = Alfred()
//
// Get the command line string and initialize the count.
//
let str: String = Process.arguments[1]
var count = 0
//
// To a Capitalized String.
//
var result = str.capitalizedString
wf.AddResult("CS\(count)", arg: result, title: "Capitalized: \(result)", sub: "Text Case Converter", icon: "icon.png", valid: "yes", auto: "", rtype: "")
count++
//
// Create a Lowercase String.
//
result = str.lowercaseString
wf.AddResult("CS\(count)", arg: result, title: "Lowercase: \(result)", sub: "Text Case Converter", icon: "icon.png", valid: "yes", auto: "", rtype: "")
count++
//
// Create an Uppercase String.
//
result = str.uppercaseString
wf.AddResult("CS\(count)", arg: result, title: "Uppercase: \(result)", sub: "Text Case Converter", icon: "icon.png", valid: "yes", auto: "", rtype: "")
count++
//
// Create an Titlecase String.
//
result = TitleCase(str)
wf.AddResult("CS\(count)", arg: result, title: "Titlecase: \(result)", sub: "Text Case Converter", icon: "icon.png", valid: "yes", auto: "", rtype: "")
count++
//
// Output the XML.
//
println(wf.ToXML())
}
//
// Method: TitleCase
//
// Description: This method converts the string given to Title Case.
//
// Input:
// str The string to convert.
//
func TitleCase(str: String) -&gt; String {
//
// Create an array of words to make lower case.
//
let lower = ["to", "an", "and", "at", "as", "but", "by", "for", "if", "in", "on", "or", "is", "with", "a", "the", "of", "vs", "vs.", "via", "via", "en"]
//
// Create an array of words that are to be upper cased.
//
let upper = ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX", "X", "HTML", "CSS", "AT&amp;T", "PHP"]
//
// Split the string by spaces.
//
var words = str.componentsSeparatedByString(" ")
//
// initialize helper variables.
//
var result = ""
var first = true
//
// Loop through each word.
//
for word in words {
//
// Create a lower case of the word and the result word as capitalized.
//
var lword = word.lowercaseString
var res = word.capitalizedString
//
// Loop through each word that should be lower case.
//
for low in lower {
if lword == low.lowercaseString {
//
// It should be lower case. Set the result word to it and break
// out of the loop.
//
res = low
break
}
}
//
// Loop through each word that should be uppercased.
//
for up in upper {
if lword == up.lowercaseString {
//
// It should be uppercase. Set the result word and break out.
//
res = up
break
}
}
//
// If it is the first word, then always capitalize.
//
if first {
res = res.capitalizedString
first = false
}
//
// Create the resulting string.
//
result += "\(res) "
}
//
// Return the result.
//
return(result)
}
}
let cv: Converter = Converter()
</pre>
<p>This code defines the <code class="inline">Converter</code> object. That object creates the different versions of the string and assigns them to the XML results list. Once completely built, it sends the XML to the output.</p>
<p>The <code class="inline">Converter</code> object has the <code>TitleCase()</code> method for creating a title case version of the string. It compares each word in the string to the lower case array and the upper case array. If found in these, it sets the word to that value. It always makes sure that the first word is capitalized.</p><p>Compiling a library to an application is a little complex. In the Terminal.app or iTerm.app program, run these command lines in the directory that contains the sources.</p><ol>
<li>xcrun swiftc -emit-library -emit-object Alfred.swift -sdk $(xcrun --show-sdk-path --sdk macosx) -module-name Alfred</li>
<li>ar rcs libAlfred.a Alfred.o</li>
<li>xcrun swiftc -emit-module Alfred.swift -sdk $(xcrun --show-sdk-path --sdk macosx) -module-name Alfred</li>
<li>xcrun swiftc -o tcconverter -I "./" -L "./" -lAlfred -sdk $(xcrun --show-sdk-path --sdk macosx) tcconverter.swift</li>
</ol><p>Once all four steps are ran, you will have the tcconverter program in that directory. If you change the tcconverter.swift code, you only have to re-run the last command. If you change the Alfred.swift code, you will have to re-run all four lines.</p>
<p>The program <strong>tcconverter</strong> should now be in the workflow directory. You can test it in the <strong>Alfred</strong> prompt:</p>
<figure class="post_image">
<img data-src="https://cms-assets.tutsplus.com/uploads/users/71/posts/21807/image/AlfredWorkflowSwift-06.jpg" alt="Testing the Code">
<figcaption>Testing the Code</figcaption></figure>
<p>The download file has all of these files and the workflow for you to examine.</p>
<h2>Conclusion</h2>
<p>In this tutorial I have shown you how to install <strong>Swift</strong> on the Mac, configure three different program editors and shells, run <strong>Swift</strong> programs in a terminal, and use <strong>Swift</strong> to build <strong>Alfred workflows</strong>. </p><p>That’s a lot of knowledge that you need to practice to remember. Therefore, go make some great <strong>Alfred workflows</strong> in <strong>Swift</strong> and share them with everyone!</p>2014-09-16T02:00:00.000Z2014-09-16T02:00:00.000ZRichard Guay