Screen capture and recording in macOS

Continuing from the articles on recording macOS and iOS screens here is another handy built in tool.

Press the key combination ⇧ ⌘ 5 and it brings the screen capture/recording menu.

You can perform all the operations available from the menu here.

Of course once we start the recording then we can see the record button in the menu bar.

Once the recording is completed you can save it as a movie file.

This unified interface now offers a lot of convenient options for capturing visual content in macOS.

Advertisement

List of macOS Terminal commands

This article lists out different macOS terminal commands you might encounter. You can use this list as a starting point in your search for a command to perform a specific task. This list is by no means exhaustive.

Basic terminal commands are not listed here. Some of them are listed in the following Terminal command articles.
Terminal Commands – Basic
Terminal Commands – Part 2
Terminal Commands – Part 3

Many of the commands have also been used in the article I wrote some time back. You can have a look at the scripts to see some of the commands being used.

To get more information about the commands simply run the following command from within Terminal Application. For example, to view the manual page for tmutil simply type:

man tmutil

For fdesetup

man fdesetup
Here is a nice command to quickly open the man page in the Preview App.
man -t tmutil | open -f -a /System/Applications/Preview.app

Note

  • This is not a complete list of commands
  • Some commands are available through the macOS Recovery Volume only
  • Some commands required other resources such as the OS installer
  • Some commands are available with certain versions of the OS only

Please read the documentation for more details. Use the commands with care. Improper use of commands may result in loss of data or damage to the computer.

Commands


Installation

CommandDescription
startosinstallUsed to start the installation of macOS from the command line.
createinstallmediaUsed to create an external install disk.

Security

CommandDescription
fdesetupManage FileVault configuration.
securityManage keychain and security settings
spctlManage security assessment policy
csrutilConfigure System Integrity Protection (SIP) settings
resetpasswordPassword reset utility located in the Recovery Partition

File System

CommandDescription
hdiutilUsed to manipulate and manage disk images.
diskutilUsed to modify, verify, & repair local disks.

Data Management

CommandDescription
tmutilUsed to configure Time Machine settings in macOS
screencaptureTakes screenshot of the specified screen and saves the image at the specified location.
mdlsUsed to get metadata attributes for a given file
mdutilUsed to manage metadata stores that are used by Spotlight

Settings

CommandDescription
defaultsUsed to modify plist files. Typically used to update preference files.
ioregUsed to view the I/O kit registry
system_profilerUsed to generate system hardware & software reports.
plutilUsed to check syntax of property lists or covert property lists from one format to another
AssetCacheManagerUtilUsed to configure content caching settings.
openUsed to open documents from within the command line.
networksetupPerform network configuration.
systemsetupUsed to configure machine settings in System Preferences.
launchctlUsed to manage and inspect daemons, agents, & XPC Services

Applications

CommandDescription
codesignUsed to create, check, display code signatures.
pkgbuildUsed to build installer packages
productbuildBuilds a product archive
installerSystem software and package installer tool

User Account Management

CommandDescription
dsclThis is a command line Directory service utility that allows us to create, read, and manage Directory Service data.
sysadminctlUser account management
passwdChange user password
loginUsed to login to another user account.

Server & Device Management

CommandDescription
profilesUsed to install, remove, list, or manage Configuration profiles.
serveradminUsed to manage the services in macOS
mdmclientLocated in /usr/libexec/mdmclient it is used to manage interactions with the MDM.
asrApple Software restore: Used to copy volumes.

Scripting

CommandDescription
osascriptUsed to execute the given AppleScript

Share any commands you may know of in the comments window.

Disclaimer

The information Is Provided “As Is”, Without Warranty Of Any Kind, Express Or Implied, Including But Not Limited To The Warranties Of Merchantability, Fitness For A Particular Purpose And Noninfringement. In No Event Shall The Authors Or Copyright Holders Be Liable For Any Claim, Damages Or Other Liability, Whether In An Action Of Contract, Tort Or Otherwise, Arising From, Out Of Or In Connection With The information provided Or The Use Or Other Dealings In The information.

Useful scripts for macOS

Getting Started

You might find these articles useful

One of the advantages with scripts is the fact that you can easily automate many tasks. Here is an article that walks you through that process.

If you come across a situation where you want to perform a set of tasks on multiple computers then scripts come in very handy.

I will be providing the Shell Script version of the task. Feel free to make changes to the scripts as required. I will try to provide an AppleScript version of the tasks a little later.

This is not the only way to implement the scripts. There may be multiple approaches towards achieving the same result. You will have to explore and examine the correct approach.

This is not a comprehensive list. The scripts should give you some ideas and act as a useful reference when you are creating your own scripts.

I have tested these scripts on macOS Catalina 10.15

Download

You can download all the scripts from here.

Script CategoryPage Number
Settings and Accounts1
Security2
Data3
Information Collection4
File System5

Disclaimer

The Software Is Provided “As Is”, Without Warranty Of Any Kind, Express Or Implied, Including But Not Limited To The Warranties Of Merchantability, Fitness For A Particular Purpose And Noninfringement. In No Event Shall The Authors Or Copyright Holders Be Liable For Any Claim, Damages Or Other Liability, Whether In An Action Of Contract, Tort Or Otherwise, Arising From, Out Of Or In Connection With The Software Or The Use Or Other Dealings In The Software.


WARNING

Please try these scripts on a test computer. Some of the scripts do make changes to the system. Always test before using these scripts.

Creating your own Drag and Drop DMG

What are Disk Images?

Disk images are a means of archiving data. They are created using a tool called Disk Utility which is a File System Management Utility of macOS. Disk Images follow the extension ‘.dmg‘ and are only compatible with macOS.

Disk Images are a popular way of distributing applications for macOS. They provide the capability of compressing large files and make delivery over the internet very easy.

In this article we are going to look at how we can create disk images for application distribution.

Creating the DMG Folder for distribution

  1. Create a Background image. This can have any design. It’s a good idea to have arrows or other visual aids to assist others during installation.
  2. Create a new Disk Image. Open Disk Utility.
  3. Click on File > New Image > Blank Image
  4. Leave the default settings as is. Choose the size that you desire.
  5. Mount the Disk Image.
  6. Create a folder called background in the mounted volume.
  7. Save the background image in the folder we just created.
  8. Now we will hide the background folder. Switch to terminal and run the following command.

     
    cd /Volume/InstallDMG/
    mv background .background
    


    Here we are simply renaming the background folder with a ‘.’ before it. This hides the folder from the GUI.

    Now we will prepare the payload. This can be any file or folder we wish to install. For the sake of this demo I will be choosing Mozilla FireFox. In reality you would be distributing your own application.
  9. Copy the FireFox app into the mounted volume.
  10. Open “Show View Options“.
  11. Restrict the mounted volume to icon view only. Feel free to customise the other settings as you wish. This includes icon size.
  12. Drag and arrange the icons in your mounted window to match the background.
  13. Eject the disk image. 
  14. Make a duplicate copy of the image file. This can act as a reference for future images you wish to create.
  15. Now we will convert the disk image into a read only compressed disk image. This will be the one that we will use for distribution. Open Disk Utility.
  16. Click on Images > Convert
  17. Select the InstallerDMG.dmg from Desktop or wherever you had saved it.
  18. Give it a new name and convert it to compressed format.

That’s it. You now have your own drag drop window ready for distribution.

iPhone Screen Recording – Part 2

This is an addendum to the earlier topic on Screen and Audio recording on macOS & iOS.

In the earlier article we had discussed how to share the iPhone screen on the project or how to record iPhone screen activities. In this article we are going to see how to use the built in feature of iOS 11 to do the same.

  1. First we must add the button to do this to control centre. Open Settings > Control Centre> Customise Controls .IMG_0134
  2. Tap on the ‘+’ button next to Screen Recording to add Screen Recording to the control centre. Close the Settings App.IMG_0135
  3. Swipe up from the bottom of the screen to bring the control centre options.
  4. Tap on the Screen record button. Tap the microphone audio button to record audio if you wish.IMG_0136
  5. Tap the “Start Recording” button to start recording. To stop simply tap on the “Stop Recording” button.IMG_0138IMG_0140
  6. The video is saved in the camera roll.

Third Party Applications

This feature is used to provide screen sharing capability via apps such as TeamViewer.

 

Screen and Audio recording on macOS & iOS

In this article we are going to look at how we can use the built in Application: QuickTime to record a screen or a movie. In fact, the videos that you are about to see in the article below were created using QuickTime.

A good reason to record the activity on the screen would be to create a visual step by step guide which can be distributed to employees in the organisation. For example, you can create a video to show employees how they can sign into their company’s email account and access it from their iPhone or Mac.

Recording your Mac’s screen

Follow the steps given below to record your Mac’s screen:

  1. Open QuickTime Player
  2. Click on File > New Screen RecordingScreen Shot 2018-01-24 at 4.46.22 PM
  3. You should see the window popping up.
  4. From the drop down next to the Record button select the audio input & whether mouse clicks should be shown.Screen Shot 2018-01-24 at 4.47.29 PM
  5. Click on the Record Button. You should see a dialog asking you whether you want to record a small area or a full screen.Screen Shot 2018-01-24 at 4.47.52 PM
  6. The recording starts once the stop button in the menu bar becomes dark.
  7. Click on the stop button to stop the recording.
    Screen Shot 2018-01-24 at 4.57.49 PM
  8. Save the file that was created.

Recording your iPhone/iPad Screen

(Mirroring your iPhone Screen on the Projector)

The process of recording the iPhone/iPad screen is quite similar to recording your computer’s screen. The key thing to remember is to connect your iPhone/iPad to the Mac with the lightning cable.

Follow the steps given below to record your iPhone/iPad screen:

  1. Open QuickTime Player
  2. Click on File > New Movie Recording
  3. You should see the window popping up.
  4. From the drop down next to the Record button select the audio input & whether mouse clicks should be shown. The difference now is the fact that you get an extra option to choose the source.

Recording a Movie

Follow the steps given below to record a Movie on your Mac:

  1. Open QuickTime Player
  2. Click on File > New Movie RecordingScreen Shot 2018-01-29 at 4.11.38 PM
  3. You should see the window popping up.
  4. From the drop down next to the Record button select the audio input. You can also select your camera source from here.
    Screen Shot 2018-01-29 at 4.21.41 PM
  5. Click record to start recording & click on the stop button to stop recording.

Recording Audio

Follow the steps given below to record an Audio on your Mac:

  1. Open QuickTime Player
  2. Click on File > New Audio RecordingScreen Shot 2018-01-29 at 4.11.38 PM copy
  3. You should see the window popping up.
  4. From the drop down next to the Record button select the audio input.
  5. Click record to start recording and stop to stop recording.

Here is a quick video on how to perform the different tasks that we have seen above.

Buyers Guide for macOS & iOS in the Enterprise

This article is more of a productivity article aimed at getting first time users up and running quickly on their Mac, iPhones or iPads. Anyone looking to buy one of these products or Tech Support teams that help employees with their computers would find this article helpful. The thoughts shared here are personal, readers are welcome to share their own thoughts and experiences.

The article is not a comprehensive guide. Its aim is to give potential users some idea as to how the devices can be used in their work environment. Specifically from an Application perspective.

Macintosh

macFamily


Which one to buy?

This depends on how the device is going to be used. Here are 3 general classifications:

Basic Usage

Basic usage would mean simple day to day tasks. These are the tasks that would qualify for:

  • Checking emails
  • Browsing the web
  • Social Media
  • Listening to Music
  • Watching Movies
  • Composing letters
  • Preparing Presentations & running presentations
  • Note taking

In such a case you may want to consider buying a MacBook or a MacBook Air. If portability is not required then a Mac Mini would also do.

At entry level configurations these devices would do the job very well.

Intermediate Usage

If the tasks being performed are a little more demanding then you may want to consider higher configuration devices. Again in most cases the  MacBook or a MacBook Air would do. If portability is not required then a Mac Mini would also do. In all these cases consider one with slightly higher configuration.

For situations where the compute power is important you may even consider the MacBook Pro. For example, if there are programmers who need to work with a high configuration Mac and they need portability, then you can consider the MacBook Pro.

Pro Usage

This indicates that the tasks being performed are very compute intensive. These are some of the job profiles which may demand compute intensive resources:

  • Programmers
  • Video Editors
  • Audio Editors
  • Post Production Teams
  • Marketing & Creative Teams
  • Scientific Research

For such situations the higher end desktops & MacBook Pros would be required. So the iMac or the highest configuration Mac Mini, or the 15″ MacBook Pro would be best suited for such environments.

In some situations even more powerful computers would be required. The iMac Pro & Mac Pro should then be considered.


Built In Applications that might be useful

Productivity Tools

There are 3 applications which are a part of the suite called iWork that are very useful in organisations.

  • PAGES: Built in word processing application. You can easily created documents, letters, reports and even have them exported in Microsoft Office compatible format.
  • KEYNOTE: Built in presentation applications. Enables you to create powerful presentations from scratch. Like Pages it is possible to create presentations that are compatible with PowerPoint.
  • NUMBERS: Built in spreadsheet application. Enables you to quickly create spreadsheets and export them to Excel if needed.

The other advantage is the fact that these applications are also accessible from the cloud. Tight integration with iCloud means that you can make changes to documents from your Mac, iPhone, iPad, or iCloud.com.

Creative Tools

There are 2 applications which are available for creative purpose. These might be handy for people working in the creative departments.

  • IMOVIE: Quick create movies using videos, audios and photos that you have.
  • GARAGEBAND: A simple Music creation application that comes with a library of different instruments.

Popular Third Party Applications

These are just some of the applications.

Office Suite

Productivity

Cloud

Creative

Security

Communication

Data Backup

Virtualisation (Running Windows or Windows Applications on the Mac)


Some tasks that can be done with built in Applications

  • Scanning Documents using Preview
  • Signing Documents using Preview
  • Record Screen Activity using QuickTime
  • Record a quick movie using QuickTime
  • Automate Tasks & create workflows using Automator
  • Encrypt Data using FileVault
  • Show your iPhone/iPad screen on a projector using QuickTime on Mac
  • Backup data using Time Machine

iPhone/iPad

iosFamily


Which one to buy?

The decision on whether to buy the iPhone &/or the iPad depends a lot on what you intend to use it for. As such the major differences between the 2 devices are:

  • iPads tend to have larger screens
  • iPhone has cellular communication capability
  • iPhones are more portable as compared to iPads
  • iPads are better suited for long duration usage
  • iPads tend to be higher powered devices

While it appears that iPads are better than iPhones, that is not necessarily the case. iPhones being smaller and more compact have many advantages too.

Ideally speaking having both, an iPhone and an iPad, is the best thing to do.

To make a decision use the task list below to help find out if you need an iPhone or an iPad or both.

Note, even though I mention that the tasks can be performed easily on an iPhone, many of the tasks can also be done very easily on the iPad. The point is to illustrate ease of use in situations where you have to perform tasks with a single hand or when you are on the move.

Tasks easily performed on an iPhone

  • Making calls
  • Messaging
  • Scheduling activities such as: Reminders, Appointments, Events
  • Taking Photos & Videos
  • Emails
  • Banking Transactions
  • Finding Transit Directions
  • Finding a Taxi
  • Making E-Payments

Tasks easily performed on the iPad

  • Writing letters & blogs
  • Creating Presentations
  • Working with spreadsheets
  • Creating posters, flyers
  • Working with business applications
  • Content creation

If you do a mixture of tasks from both the lists then getting both an iPhone as well as an iPad is a good idea.

A thing to keep in mind is that the Pro version of the iPad also has a nice keyboard accessory as well as the  Pencil available. These 2 products make the whole experience so much better.

Screen size consideration

iPhone and iPad screen sizes vary quite a bit. Here are some tips on the tasks which can be best performed on specific screen sizes.

Creative Work

Generally speaking, creative tasks require a large screensize. So for an iPhone the smallest screen you should have is 4.7″. Similarly for the iPad the smallest screen you should have is the  9.7″.

Documents, letters, spreadsheets

These tasks are better performed on the iPads as such you can go for any screen size in them. Of the lot, its a lot easier to create documents and letters on the phone than spreadsheets. Again, for phones one should the larger the screen size the better.

Presentations

Like documents and spreadsheets presentations are a lot easier to create on the iPad. They can also be created from the phones. The larger the phone the better.

Messaging & Communication

This is one aspect where the screen size is not so much of an issue. In fact, some users may find the smaller screen size a lot better. Typically, the iPhone is a much better device than the iPad for this.

Productivity & General Tasks

This includes calling taxis, ordering food, taking notes, control keynote presentations, setting up appointments and reminders. These tasks are also best performed on iPhones. They can be done well with the iPad too.


Built In Applications that might be useful

Productivity Tools

There are 3 applications which are a part of the suite called iWork that are very useful in organisations.

  • PAGES: Built in word processing application. You can easily created documents, letters, reports and even have them exported in Microsoft Office compatible format.
  • KEYNOTE: Built in presentation applications. Enables you to create powerful presentations from scratch. Like Pages it is possible to create presentations that are compatible with PowerPoint.
  • NUMBERS: Built in spreadsheet application. Enables you to quickly create spreadsheets and export them to Excel if needed.

The other advantage is the fact that these applications are also accessible from the cloud. Tight integration with iCloud means that you can make changes to documents from your Mac, iPhone, iPad, or iCloud.com.

Creative Tools

There are 2 applications which are available for creative purpose. These might be handy for people working in the creative departments.

  • IMOVIE: Quick create movies using videos, audios and photos that you have.
  • GARAGEBAND: A simple Music creation application that comes with a library of different instruments.

Other Apps

  • Notes
  • Voice Memos
  • Files

Popular Third Party Applications

Office Suite

Productivity

Cloud

Creative

Security

Communication


Some tasks that can be done with built in Applications

  • Scanning Documents using Notes
  • Recording Voice Memos
  • Control HomeKit devices
  • Edit PDFs through iBooks
  • Create PDF documents through pages & then edit the PDFs either through iBooks or markup utilities
  • Record and Edit videos using the camera & iMovie

Useful iPad Accessories

 TV

There are a few things that can be done with the  TV. It can be used to mirror both macOS & iOS Devices. In which case apps such as Reflector are not really required.

It is very easy to setup and use. This can make projecting both the iPad screen as well as the iOS Screen very easy & it allows you to move across the room as you are not physically wired to the projector.

Final Word

As we can see there are a wide variety of apps available both for macOS & iOS. These include built in apps as well as Third party apps. The community of developers creating these apps is strong and growing. There are many more apps which can be used for a wide variety of purposes.

This article should give the user a fair idea as to the capabilities of devices such as iPads, MacBooks and the rest of the line up. The good thing is that for enterprise environments its easily possible to create apps that are tailored to the needs of that organisation and this makes the devices much more attractive.

When to use Swift & when to use Objective-C?

Over the past few years I have received a number of questions with regards to Swift & Objective-C. Specifically related to the future of the 2. I will try to address those questions in the form of an FAQ.

Should I learn Swift or Objective-C?

This is a question that I get from developers new to iOS/macOS App Development. Ideally speaking, you should learn Swift. As that is going to become the main language for App development on Apple’s ecosystem. However, the reality is a little different. There are a large number of applications that are written in Objective-C. You are likely to encounter them at your workplace. You may also have to maintain, upgrade & improve those apps. In such a case, it makes sense to learn Objective-C too.

Can I mix Swift & Objective-C in the same project?

Yes! But remember that you should check for feature compatibility between the 2 languages. Adding Swift code to an Objective-C project may not be very beneficial as only those features that are compatible with Objective-C can be written in Swift.

Going the other way round is not a problem. You can read more about that here:Mixing Swift & Objective-C

Will Objective-C be deprecated in the future?

That is an interesting question. There is no formal announcement from Apple stating the Objective-C is going to be deprecated. However, one can expect more attention to be paid to Swift. That is where most of the newest techniques, tools & technologies are going to be available. Objective-C will keep running as it is as of now.

Can I mix Swift with other Programming Languages?

Swift can easily be mixed with Objective-C. If you wish to incorporate C++ or C code in your Swift Project then wrapping them in Objective-C code allows you to achieve this.

Apart from that Swift does support working with C code code. You can read about that here:Interacting with C APIs.

Swift does not provide interoperability support for any other languages as of now.

Which version of Swift should I use?

It is recommended that you use the latest available version of Swift. However, the actual version that you work on depends on many other factors like: compatibility with OS Versions, support & business related choices.

Why shouldn’t we just convert all our Objective-C code to Swift and keep things simple?

A very tempting proposition. However, practical realities prevent us from doing this. The process of converting from Objective-C to Swift is time consuming. Apart from having to convert the syntax, the code also needs to be optimised taking into account the new features that are available. This will mean extensive testing and quality assurance. Most companies will not invest their resources into this endeavour.

A better approach is to migrate to Swift gradually. Here are some ways to do this:

  1. If its a brand new product/app that you are creating, start it in Swift.
  2. Any new reusable code components that are being created should be done in Swift (they should be Objective-C compatible if you intend to use this code in Objective-C projects).
  3. If any part of a product is going to undergo heavy change, either due to a bug fix or a new feature. This is a good time to convert it into Swift.

A good example is how Apple is approaching the process of migrating to Swift. They are doing it component by component.

I have been developing apps in Objective-C for some time. I am able to create any reasonably complicated app now. If Objective-C hasn’t been deprecated then should I start making apps in Swift?

This is a choice that you have to make. It is recommended that new apps (at the very least) be made in Swift as that is the language that will undergo the maximum amount of changes & improvements in the future.

What do you suggest as a trainer?

Another question that I get very often. It depends on the situation. I would say learn both Swift & Objective-C. You can skip learning Objective-C if you are confident that you will not have to work with any projects written in that language.

If I am starting on a brand new project I would use Swift. But if its an Objective-C project I would stick to Objective-C.

Can Swift development only be done on macOS?

No! Swift development can also be done on Linux. However, iOS/macOS/tvOS/watchOS App Development can only be done on macOS through Xcode.

How should I migrate to Swift?

There are different approaches that one can use. It all depends on the situation and needs of your organisation. Here are some things that you can do:

  • Start development of brand new apps (from scratch) in Swift.
  • If you are creating a brand new library which will be used for future projects then go ahead with Swift.
  • If a major component of an existing app is going to be changed significantly then you can go ahead with Swift.

You can do all or some of the above. There may be other strategies too. You should also factor in the cost of migration from one language to another.

 

Collection Type, Sequence Type & Indexable Type

This is for Swift Version 2.2 & earlier. I will be adding the snippet of code for the changes the Swift 3.x have introduced.

What are the Collection Type & Sequence Type Protocols?

The Collection Type, Sequence Type & Generator Type Protocols define rules that govern how different data structures or collections of data can be used, interacted with and operated within the Swift programming language. The CollectionType is a special case of the SequenceType.

Why do we need such Protocols?

Lets take the example of the Swift For-Loop.

var arrOfStrings : [String] = [String]()

arrOfStrings.append("Jill")
arrOfStrings.append("Jack")
arrOfStrings.append("John")
arrOfStrings.append("Jane")

for name in arrOfString
{
     print("The name is \(name)")
}

Now, if we have created our own data type. We would not be able to use the above for-loop as it would not conform to the … type protocols. The for-loop is expecting a data structure that acts and behaves in a way that is governed by the … protocols.

Just like the for-loop example above there are many other features within the Swift Programming Language that expect data structures to act and behave in a particular way. By designing our data structures to conform to these protocols we can make the easily compatible with the existing code and language features out there.

How do we use these protocols for our own data structures?

First we need to decide what kind of collection are we making. For the sake of this example I will create a Custom Stack.

class CustomStack<Element>
{
    var data : [Element] = [Element]()

    func push(Element newElement : Element)
    {
        data.append(newElement)
    }

    func pop() -> Element
    {
        return data.removeLast()
    }
}

The above code is very simple for the purpose of this exercise. Its a stack. Which is internally really an Array. It has functions to push data and pop data. We are now going to convert this type to a collection to conform to the CollectionType protocol.

Implementing the Indexable Protocol methods

As a first step we are going to make our CustomStack conform to the Indexable Protocol.

extension CustomStack : Indexable
{
    //INDEXABLE PROTOCOLS
    typealias Index = Int

    var startIndex : Int
    {
        return 0
    }

    var endIndex: Int
    {
        return (data.count - 1)
    }

    subscript (position : Int) -> Element
    {
        return data[position]
    }
}

The above change makes the data structure conform to the Indexable protocol. This is a requirement for it to be of type CollectionType. In order to conform to the Indexable protocol we need to implement a few computed properties. Let us look at the changes

typealias Index = Int

This line informs the system that the Indexing type for my data structure is an Int.

var startIndex : Int
{
    return 0
}

var endIndex: Int
{
    return (data.count - 1)
}

The next 2 are computed properties. Each provides the implementation of the startIndex  and endIndex properties. Note that the type for both is Int as we have declared the Index type earlier as Int.

subscript (position : Int) -> Element
{
    return data[position]
}

The last implementation is of subscript. This provides the implementation to access an Element from the Stack using the Subscript operator.

Implementing the Sequence Type Protocol

Next we will implement the Sequence Type Protocol methods.

extension CustomStack : SequenceType
{
    typealias Generator = AnyGenerator<Element>
    
    func generate() -> Generator
    {
        var index = 0
        
        return AnyGenerator(body: {() -> Element? in
            if index < self.data.count
            {
                let res =  self.data[index]
                index += 1
                return res
            }
            return nil
        })
    }
}

Let us examine this code line by line.

typealias Generator = AnyGenerator<Element>

Objects of type Generator allow us to navigate through our collection. Quite like how iterators  work in C++. This line specifies the type to be AnyGenerator for Elements.

func generate() -> Generator

Next we start the implementation of the generate function. This is required as part of the SequenceType protocol.

var index = 0

This index variable is used to track the element that is currently being accessed.

return AnyGenerator(body: {() -> Element? in
            if index < self.data.count
            {
                let res =  self.data[index]
                index += 1
                return res
            }
            return nil
        })

The return statement is the main statement. Here we are creating an object of type AnyGenerator. As an argument to the constructor call we are passing in a closure that will be used to iterate through the sequence. Note that the closure captures the index variable and holds a reference to its value even though we have left the original function.

Implementing the Collection Type Protocol

Next we will implement the Collection Type Protocol methods. We don’t really need to implement a lot in order to conform to the CollectionType protocol. In fact, if we just conform to the CollectionType protocol and use the implementations of the previous 2 extensions we should be just fine. However, for the sake of demonstration we are implementing the subscript functionality within the CollectionType.

extension CustomStack : CollectionType
{
    typealias SubSequence = CustomStack<Element>
    
    subscript (bounds: Range<CustomStack.Index>) -> CustomStack.SubSequence
    {
        let newStack : CustomStack<Element> = CustomStack<Element>()
        
        for i in bounds.startIndex...bounds.endIndex
        {
            newStack.push(Element: data[i])
        }
        return newStack
    }
}

Let us look at the code line by line.

typealias SubSequence = CustomStack<Element>

Again, as before this line indicates that the SubSequence type is actually a CustomStack.

subscript (bounds: Range<CustomStack.Index>) -> CustomStack.SubSequence

Here we start the implementation of the subscript functionality.

let newStack : CustomStack<Element> = CustomStack<Element>()
        
for i in bounds.startIndex...bounds.endIndex
{
     newStack.push(Element: data[i])
}
return newStack

The rest of the code is the implementation of the subscript range behaviour. One can have different implementations to achieve the same result.

CollectionType Video

Conclusion

As we can see, by designing our data structure to conform to a particular set of protocols. We have made it possible for our data structure to take advantages of the different features, functionalities and even API’s available within the Swift Language and the Frameworks used as a part of iOS, macOS, watchOS & tvOS development.