Category Archives: EnvatoTutsCode

Quick Tip: Enumerations in Swift

Enumerations are a common design pattern in many programming languages. While you may be familiar with enumerations in C and Objective-C, Swift’s implementation of enumerations is significantly more powerful and flexible. In this quick tip, you’ll learn what’s special about enumerations in Swift, how to use them in your projects, and what makes them so powerful.

1. What Is an Enumeration?

Enumerations aren’t new and they’re certainly not unique to Swift. However, if you’re familiar with enumerations in C, then you’re going to love Swift’s powerful take on enumerations.

If enums or enumerations are new to you, then you may not be familiar with what they have to offer. In Swift, enumerations are first class types that define a list of possible values for that type.

An example might be the possible states of a network connection. The possible states could be:

  • disconnected
  • connecting
  • connected

We could add a fourth state for the case the state is unknown. With this example in mind, let’s see how to define and implement such an enumeration.


Like I said, enumerations are first class types in Swift. An enumeration definition looks very similar to a class or structure definition. In the example below, we define the ConnectionState enumeration.

enum ConnectionState {

The name of the enumeration is preceded by the enum keyword and followed by a pair of curly braces. The ConnectionState enumeration will define the possible states of a network connection. To define these states, we add member values or members to the enumeration’s definition. The definition of a member value always starts with the case keyword.

enum ConnectionState {
    case Unknown
    case Disconnected
    case Connecting
    case Connected

In C or Objective-C, the above enumeration would look a bit different as illustrated in the example below. Each value of the enumeration corresponds with an integer, for example, ConnectionStateUnknown equals 0, ConnectionStateDisconnected equals 1, etc.

typedef enum : NSUInteger {
} ConnectionState;

This isn’t true in Swift. The members of an enumeration don’t automatically correspond with an integer value. The members of the ConnectionState enumeration are values themselves and they are of type ConnectionState. This makes working with enumerations safer and more explicit.

Raw Values

It is possible to explicitly specify the values of the members of an enumeration. In the following example, the members of the ConnectionState enumeration have a raw value of type Int. Each member is assigned a raw value, corresponding with an integer.

enum ConnectionState: Int {
    case Unknown = -1
    case Disconnected = 0
    case Connecting = 1
    case Connected = 2

Note that we specify the type of the raw values in the enumeration’s definition and that no two member values can have the same raw value. If we only specify a value for the Unknown member, then Swift will automatically increment the value of the Unknown member and assign unique values to the other members of the enumeration. To better illustrate this, the below example is identical to the previous definition of the ConnectionState enumeration.

enum ConnectionState: Int {
    case Unknown = -1
    case Disconnected
    case Connecting
    case Connected

read more

Try Our Course on PHP Design Patterns With a Free Trial

Final product image
What You’ll Be Creating

No matter what your level of skill, studying design patterns can make your code better. They are solutions to problems that every developer faces with just about every application that they write. 

In our comprehensive course, PHP Design Patterns, Envato Tuts+ instructor Jeremy McPeak will walk you through some of the most fundamental design patterns and show you how to implement them in PHP. For each pattern, you’ll see a real-world example of that pattern in use, as well as a complete implementation in PHP.

read more

What Is WP-CLI? A Beginner’s Guide

WP-CLI has been around for quite some time now (circa 2011) and has steadily gained momentum in the WordPress developer community. But what is it exactly, and how can you use it in your WordPress workflow?

The idea behind WP-CLI is that it allows you to interact with, and manage, WordPress sites via a command line interface. According to the official documentation, it’s a command line alternative to using the traditional WordPress admin user interface.

The command line approach makes sense as you can typically do things on a computer much quicker via the command line, and the WP-CLI is no different. If you’ve ever used the command line on Windows, or the Terminal on macOS, then you’ll be right at home using the WP-CLI.

However, this is a tutorial aimed at beginners, so don’t worry if you’re not a command line guru. If you’ve never used the WP-CLI or the command line before, then you’re in good company and definitely in the right place!

Before we go any further, I’ve a confession to make. As I hinted above, I’ve never actually used the WP-CLI before! I’ve known about it for quite a while and have been itching to try it out, but never gotten around to actually installing it and using it. Until now, that is…

So we’ll be literally in this together and working out how to use the WP-CLI both as complete beginners. I’m really interested to see how the WP-CLI fits into my existing WordPress development workflow and if it can help boost productivity.

Are you ready to get started? OK then, let’s go!

Installing WP-CLI

Installing the WP-CLI for the first time can seem a bit daunting. I had to read the installation instructions a couple of times before it made sense. But, as it turns out, it isn’t that difficult once you understand exactly what’s required.

To start with, we need to get the latest version of WP-CLI. The recommended way to do this is to download the WP-CLI as a Phar file via the command line. This is just a PHP archive file containing all the PHP files needed for the WP-CLI to run, all wrapped up in a single convenient file ready for us to download.

Installing on macOS

Open up a terminal window and type in the following:

$ curl -O

This will download the WP-CLI Phar file to your computer. Let’s check everything’s OK by testing the WP-CLI archive.

php wp-cli.phar --info

You should see output similar to the following:

PHP binary:    /usr/bin/php
PHP version:	5.6.30
php.ini used:
WP-CLI root dir:	phar://wp-cli.phar
WP-CLI packages dir:
WP-CLI global config:
WP-CLI project config:
WP-CLI version:	1.1.0

To make using the WP-CLI more convenient, we want to be able to run it from anywhere and via a shorter command such as wp rather than having to type in wp-cli.phar every time.

We can do this via the following two commands:

chmod +x wp-cli.phar
sudo mv wp-cli.phar /usr/local/bin/wp

Now try to run wp --info in a terminal window (pointing to any directory). If you see the same output as earlier when you ran php wp-cli.phar --info then you’re in business. WP-CLI is set up and ready for use!

There are other ways you can install WP-CLI, such as via Composer, so you might want to check out the alternative methods if you’re struggling with the recommended default method.

Installing on Windows

Installing on Windows is slightly more involved, as PHP isn’t available from the command line by default. You can install PHP manually, but the easiest way is to use a local development server such as MAMP because PHP is automatically installed as part of the overall package.

Once PHP is available on your system you’ll need to find the path to the PHP executable and make it available globally (this is covered in detail in the PHP Manual).

With PHP installed and available from any directory, download the wp-cli.phar file manually and save it to a folder such as c:\wp-cli. To be able to run the WP-CLI via the wp command just like we did on macOS, create a batch file called wp.bat inside the same folder you saved the wp-cli.phar archive file.

Add this to the batch file:

php "c:/wp-cli/wp-cli.phar" %*

Finally, add c:\wp-cli to your global path:

setx path "%path%;c:\wp-cli"

The WP-CLI should now be available from any command line window.

An Even Easier Way!

If you’re feeling a little bit lost right now then I may have a lifeline for you. If you’re a DesktopServer user then WP-CLI is extremely easy to set up. Since DesktopServer 3.8.2, a new developer plugin is available which installs the WP-CLI on all your development sites!

Installing WP-CLI Using DesktopServer

Once it’s activated, you can access the WP-CLI via the main DesktopServer site list, or the WordPress Toolbar.

Access WP-CLI via the web browser
Accessing WP-CLI via WordPress

If you do have access to DesktopServer then I’d definitely recommend installing the WP-CLI this way, as it’s by far the simplest setup method. I’ve used DesktopServer for the last couple of years, so I’m lucky that WP-CLI installation was a breeze for me.

Using WP-CLI Remotely

This tutorial is aimed at beginners who are new to the WP-CLI, using a local WordPress installation. However, if you want to execute commands on a remote server (i.e. a live WordPress site) then you can still follow along if you have WP-CLI installed.

You’ll need to be able to connect to the server via an SSH client and have your hosting account login details handy. Once connected and logged in, you’ll be able to use all the WP-CLI commands in this tutorial.

It’s worth contacting your host to see if they support the WP-CLI as installing it will be much simpler.

Testing the Waters

Hopefully by now you’ll have the WP-CLI installed, in which case you can relax a bit as you’ve just done the hardest part!

Open up a command line window in the root directory of the WordPress website you want to work with, which should look similar to the screenshot below.

Preparing to use WP-CLI

One advantage to using DesktopServer is that it automatically opens a command window pointing to the correct root WordPress site directory. I thought that was a nice touch, especially if you’re working on multiple sites.

Let’s now test our installation of WP-CLI. This is our first command…

wp --info
PHP binary:     C:\xampplite\php\php.exe
PHP version:    5.5.24
php.ini used:   C:\xampplite\php\php.ini
WP-CLI root dir:        C:\xampplite\ds-plugins\ds-cli\vendor\wp-cli\wp-cli
WP-CLI packages dir:
WP-CLI global config:
WP-CLI project config:
WP-CLI version: 1.0.0

read more

SpriteKit Basics: Nodes

SpriteKit is Apple’s 2D game engine—a rendering engine built on top of OpenGL. It was introduced with iOS 7, and each subsequent release has brought great additions to the framework. With the use of textured sprites, a built-in physics engine, and the very powerful SKAction class, you can very quickly build functional 2D games.

SpriteKit has built-in editors for scenes and particles, a camera node since the release of iOS9, and built-in support for tilesets since the release of iOS 10. With these new additions, SpriteKit is quickly becoming a powerhouse for creating 2D games.

To follow along with this tutorial, just download the accompanying GitHub repo. It has a folder called ExampleProject Starter. Open the project in that folder in Xcode, and you’re ready to go!


Nodes are the fundamental building blocks of SpriteKit, and SKNode is the base class of all nodes. All of your
onscreen assets will be an SKNode or a subclass thereof. SKNodes by
themselves do not provide any visual content, however. All visual content is
drawn using one of a number of predefined SKNode subclasses. SKNodes
and its subclasses share several properties you can alter. Some of
the more important ones are as follows.

  • position (CGPoint): the node’s position within its parent’s coordinate system
  • xScale (CGFloat): scales the width of a node by a multiplier
  • yScale(CGFloat): scales the height of a node by a multiplier
  • alpha (CGFloat): the transparency of the node
  • zRotation (CGFloat): the Euler rotation about the z axis (in radians)

One of the most important SKNodes is the SKScene. This is the root node to which all other nodes are added. By itself, SKScene does not provide any visual elements, but it displays the nodes which are added to it.

Scene Nodes

SKScenes are the root nodes to which all other nodes are added. The scene animates and renders the content from its child nodes. To display a scene, you add it to an SKView (which is a subclass of UIView and therefore has many of the same properties as UIView).

In the SpriteKit starter project, the initial scene is showing when the project loads. For now, this is just a blank black screen. It is shown when the GameViewController invokes presentScene(_:) on the view instance, passing in the scene as a parameter:

override func viewDidLoad() {
    let scene = GameScene(size:CGSize(width: 768, height: 1024))
    let skView = self.view as! SKView
    skView.showsFPS = false
    skView.showsNodeCount = false
    skView.ignoresSiblingOrder = false
    scene.scaleMode = .aspectFill
    skView.presentScene(scene) // Present the Scene

Don’t worry about the other options for now; I’ll explain them later in this series.

Creating a Scene

Many games have more than one screen or scene, so we will create a new scene from scratch and then show it from our initial scene.

Select File > New > File from Xcode’s menu, and choose Cocoa Touch Class.

Choose the Cocoa Touch Class template

Make sure Class is set to NewScene and that Subclass of is set to SKScene. Press Next and then Create, making sure the main target is checked. Below is the code for the NewScene.swift.

import UIKit
import SpriteKit

class NewScene: SKScene {


Now we have two scenes in our project, and neither has any visual content. Let’s add an SKLabelNode (like all nodes, this is a subclass of SKNode). The SKLabelNode‘s sole purpose is to display a text label.

Label Nodes

Label nodes, implemented in the SKLabelNode class, are used to show text within your game. You can use custom fonts if you wish, but for our purposes we will just stick to the default, which displays white text and is set to Helvetica Neue Ultra Light, 32 point.

Add the following inside the didMove(to:) method within GameScene.swift. This method is called immediately after a scene is presented by a view. Generally, this is where you would set up any of your game’s assets and add them to the scene.

override func didMove(to view: SKView) {
    let startGameLabel = SKLabelNode(text: "Start Game")

read more

How to Zip and Unzip Files in CodeIgniter

The first half of this tutorial explains different ways you can create a zip file using built-in CodeIgniter APIs. We’ll see how to create and save zip files on the server and how you can make them available for download to end users as well.

The second half includes a discussion of how you can unzip the file. To demonstrate that, we’ll build a custom page that allows users to upload zip files that will be extracted on the server after successful file upload. To achieve the desired functionality, the ZipArchive PHP extension comes to our rescue!

Before we go ahead and actually dive into the development stuff, I’ll list the files that we’re going to develop over the course of this tutorial:

  • application/controllers/Zip.php: It’s a controller file that demonstrates various ways you could create a zip file.
  • application/controllers/Unzip.php: It’s a controller file that includes the code used to unzip a user-uploaded file.
  • application/views/file_upload_form.php : It’s a view file that holds pretty basic HTML file upload form code.
  • application/views/file_upload_result.php: It’s a view file that shows the result of a user-uploaded file; basically it tells you if the file was successfully unzipped.
  • application/libraries/Extractor.php: This file demonstrates the concept of a custom library in CodeIgniter.

With everything in place, we’re ready to move on to our next section!

How to Zip Files?

Go ahead and create a file application/controllers/Zip.php with the following contents.

// application/controllers/Zip.php
defined('BASEPATH') OR exit('No direct script access allowed');

class Zip extends CI_Controller {
    private function _load_zip_lib()
	private function _archieve_and_download($filename)
		// create zip file on server
		// prompt user to download the zip file

	public function data()
		$this->zip->add_data('name.txt', 'Sajal Soni');
		$this->zip->add_data('profile.txt', 'Web Developer');

	public function data_array()
		$files = array(
				'name.txt' => 'Sajal Soni',
				'profile.txt' => 'Web Developer'

	public function data_with_subdirs()
		$this->zip->add_data('info/name.txt', 'Sajal Soni');
		$this->zip->add_data('info/profile.txt', 'Web Developer');

	public function files()
		// pass second argument as TRUE if want to preserve dir structure
	public function dir()
		// pass second argument as FALSE if want to ignore preceding directories

read more