Two weeks of a Swift Course and Two Apps on the App Store

Alexandre started the Swift and iOS 8 Apps in 31 Days course and already has two apps on the App Store. Learn about his background and how he's spent his time learning to program new iPhone apps in Swift.

I have found his work to be very inspiring and I hope that you join me in making and selling your first iPhone app.

Not only has he submitted multiple apps to the App Store, but he's also been blogging about the process, struggles, and accomplishments. If you want to learn, this is one of the best ways to get started.

Learn about Alexandre's programming experience and work ethic.

What's your work/education background?

I have a French management business school degree. I'm an entrepreneur; in 2000 I built a recruiting agency in the information technology field.

In 2009, with two partners we created a software company that developed recruitment software in the cloud.

I'm in charge of the sales department.

When did you start programming in Swift? 

I started programming in Swift on September the 20th, after Apple released Xcode 6.0 

Did you have any programming experience before starting Swift?

I have a little experience in Python (our developer team works in Python, so I’ve learned the language to be able to understand them). A long time ago, I played with my HP48 calculator in a language similar to Pascal.

How much time have you spent each week working on programming?

I was really invested in learning Swift and I’ve spent ten to fifteen hours each day for three weeks to catch up on the iOS Developer.

Now I spend four to five hours a day working with Swift.

What do you recommend to other students who are learning Swift?

I would recommend coding their own projects while learning on good materials. I've found it very effective to follow great courses/learning resources and mix that with my own code at the same time.

Watching a video or reading a tutorial is great, but it will bring all its power if you try to make something on your own with that new knowledge. 

Did you have any issues or problems when you were learning Swift?

The main issue was before the beginning, when I tried to picture the amount of things to learn (the language, its concepts, Xcode, Cocoa, etc., etc.). It could be overwhelming.

But "the goal is the way." If you start with a good teacher, it is not about the mountain to climb but about the next step to take.

One step at a time on the right road and everything begins to feel accessible. It is a great journey and a lot of fun. 

How many apps have you submitted to the App Store?

I have two apps on the App Store.

Table Plan

Table Plan

Table Plan was a development to test if I could build an App. It was a nice learning project because it dealt with math (ellipse), gestures, popover and access to the address book. I'm happy to have published the app, because my mother uses it now. :)

Casual Poet

Casual Poet

Casual Poet is the result of the first App Challenge. It was an insane weekend of development (near forty hours of work in two days). But what a pleasure at the end to have something that looked like a complete App.

It’s more of a proof of concept right now, and it needs more developments to become a real game. I'm working on it now. 

Do you like making apps? What's your goal?

Making apps is really fun and rewarding. It is like a painting: at the end we have created something.

I want to take time to give back to the Swift community too. I've started a blog to share some coding topics I encountered during my developments that could help other developers.

My goal is to continue learning and build great apps. I'm really exited with the Apple Watch. Next year will be a great coding year.

The next step will be to release an App with a high level of quality and a profitable economic model.

Final Words

Awesome Thanks for all the insight into making apps with Swift! Follow Alexandre on Twitter or read his Swift programming blog!

Connect

Return Type Error Messages are Wrong in Swift

Error messages from Xcode have a tendency to be wrong. A bad error message can send you searching in the dark in the wrong direction.

I want to share my process for searching for answers using Google and strategies that you can leverage in code to help you overcome some obstacles with Swift’s error prone error messages.

It seems that I find more wrong error message in Swift than from my experiences with Objective-C. However, that could also be attributed to my ability to fix common errors before Xcode had time to tell me what it thought was wrong in Objective-C.

I do know that I learn the most when I encounter errors and figure out how to fix them. As a beginner programmer, you will need to start identifying errors as you type them, or after Xcode points out an error message.

I’ll show an example using an error message that had me stumped, until I revisited it the next day.

Swift Compiler Error

/Users/paulsolt/Downloads/Word Magnet/Word Magnet/ViewController.swift:173:12: Cannot invoke 'init' with an argument list of type '(x: $T4, y: $T9)'

Code

func randomInt(number: Int) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

func randomInt(number: CGFloat) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

func randomPointInRectangle(rectangle: CGRect) {
    // Attempt 1
    return CGPoint(x: randomInt(rectangle.size.width), y: randomInt(rectangle.size.height))
} 

Ok, can you guess what’s wrong?

Google to the Rescue

I didn’t find the error message helpful, so I resorted to Googling it. Search the error message, and remove the file path and line numbers.
You can open the Issue Navigator and then right-click on an error to copy the error message to a web search bar.

Search 1

Cannot invoke 'init' with an argument list of type '(x: $T4, y: $T9)’

Nothing sticks out to me on this first search. I see MIPS assembly results from the $T4 and $T9, which look like hardware registers from assembly language. That won’t help you.

Search 2
Some of the error message is error specific, and doesn’t search well. Let’s cleanup the search text.

  1. You’ll need to remove the uniquely identifying information highlighted in bold. 
  2. Add Swift to the front of the search term. 
  3. Remove the single quotes.
Cannot invoke 'init' with an argument list of type '(x: $T2, y: $T5)’

becomes

Swift + Cannot invoke with an argument list of type (x: , y: )

The first result is good, but it’s not going to help us. It’s not the real problem that you have here. The first result is actually related to the reason I started writing this code.

http://stackoverflow.com/questions/24108827/swift-numerics-and-cgfloat-cgpoint-cgrect-etc

With two searches and you are still not understanding what is wrong. That’s normal when you first start programming. The results we found are relating to mixing Double, Int, and CGFloat types together, but that’s not the problem we’re facing.

What to do when Google Fails?

Next step when I have an issue like this is to try rewriting the line of code in a different way. You can write code that’s more verbose and that does less work on a single line of code. Separate complex statements into a separate lines of code.

Make a hypothesis and test it

Maybe there is something wrong with the randomInt() function, lets use just a number.

Workflow Tip

  1. Copy and paste the offending line of code.
  2. Comment out the first line, and alter the second line of code.

Swift Compiler Error

/Users/paulsolt/Downloads/Word Magnet/Word Magnet/ViewController.swift:174:12: Cannot invoke 'init' with an argument list of type '(x: IntegerLiteralConvertible, y: IntegerLiteralConvertible)'

Code

func randomInt(number: Int) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

func randomInt(number: CGFloat) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

func randomPointInRectangle(rectangle: CGRect) {
    // Attempt 2
    //    return CGPoint(x: randomInt(10), y: randomInt(10))
    return CGPoint(x: 10, y: 10)
} 

The error message is a little different, but very similar. Swift is still having an issue with the init method for the CGPoint. 

Break apart lines of code into multiple steps

What happens when you separate the CGPoint initialization from the return statement?

Swift Compiler Error

/Users/paulsolt/Downloads/Word Magnet/Word Magnet/ViewController.swift:176:12: 'CGPoint' is not convertible to '()'

Code

func randomInt(number: Int) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

func randomInt(number: CGFloat) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

func randomPointInRectangle(rectangle: CGRect) {
    // Attempt 3
//    return CGPoint(x: randomInt(10), y: randomInt(10))
//    return CGPoint(x: 10, y: 10)
    let point = CGPoint(x: 10, y: 10)
    return point
} 

Notice how the error message has changed?

Search 1

'CGPoint' is not convertible to ‘()’

The search results aren’t very conclusive, nothing seems to show up that’s related in the first set of results. Let’s try a different approach.

Search 2
google.com will strip a lot of special characters, let’s alter the search and try it on DuckDuckGo.com

"CGPoint is not convertible to ()” 

The search returns one related result, and it’s the solution to our problem.

https://duckduckgo.com/?q=%22CGPoint+is+not+convertible+to+%28%29%22

Swift Language Programming Guide

Reading or skimming the programming guide on Swift can also help you identify problems. If you’ve never coded before I’d recommend to type in some of the examples as you read, or you can take my online Swift courses.

If you read the Swift Language Programming Guide on Functions, you might have a vague idea of what the error is. Upon seeing the error I remember back to something I read in the book.

Strictly speaking, the sayGoodbye function does still return a value, even though no return value is defined. Functions without a defined return type return a special value of type Void. This is simply an empty tuple, in effect a tuple with zero elements, which can be written as ().

What Xcode is trying to tell you is that it cannot convert a type CGPoint into nothing (an empty tuple). It’s referring to the return type, and if you look at the function signature for randomPointInRectangle you’ll notice that the return type is missing.

Solution

Don’t forget to include your return type in the function definition if you write return at the end of a function.

You can get some pretty strange and indirect error messages. Go back and fix the code to include the return type and the original logic.

func randomInt(number: Int) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

func randomInt(number: CGFloat) -> Int {
    return Int(arc4random_uniform(UInt32(number)))
}

func randomPointInRectangle(rectangle: CGRect) -> CGPoint {
    return CGPoint(x: randomInt(rectangle.size.width), y: randomInt(rectangle.size.height))
} 

You have learned how to search for a solution to an error message, how to use DuckDuckGo.com when Google fails, and how to rewrite code to improve error messages in Swift.

Connect

Share the post if you found it helpful, or comment below.

Videos Courses - Calculate Total Duration

Paul Solt Swift iPhone App Expert

I record a ton of videos on iPhone app programming, and I didn't have a good way to get the total time for a course from a set of videos.

I previously used VLC, but that gets out of hand when you have 30+ videos to manually calculate total duration.

Day 1 videos are just the beginning

Day 1 videos are just the beginning

I wrote a script in Python, since the mdls command didn't seem to work in Swift. Maybe next time it'll be Swift.

Run this code in Terminal and it'll calculate the lengths of all the .mp4 videos and output them to the console. It doesn't work with other video types, but you can grab the code and tweak it. I export all my videos with handbrake (normal settings), which gives me .mp4 video files that are small.

As of now, I have 101 videos from the first 14 days of my Swift iPhone programming course. Using this script I have a total of 12 hours 32 minutes of content.

Run the code

Open Terminal on Mac using Spotlight (Command + Spacebar) > type Terminal > Press enter

python VideoDurationCalculator.py /path/to/your/video/folder

Example:

python VideoDurationCalculator.py /Users/Shared/Course\ Videos/1\ -\ Swift\ in\ 31\ Days/Swift1\ -\ Export\ 1080

VideoDurationCalculator.py

import os
import commands
import sys

# Paul Solt - get the length of all videos within a folder (recursive)
#
# Depending on the number of files/folders, it can take time to complete
#(100 files ~2.018 seconds to run)

# Set your video folder path here
defaultPath = "/Users/Shared/Course Videos/1 - Swift in 31 Days/Swift1 - Handbrake 1080"


def main():
    path = defaultPath

    if len(sys.argv) == 2:
        path = sys.argv[1]
    else:
        print "Notice: Using default path:", defaultPath, "\n"

    #test path
    if os.path.exists(path):
        # Grab all the video (.mp4) files recursively for a folder
        filenames = []
        for root, dirs, files in os.walk(path):
            for file in files:
                if file.endswith(".mp4"):
                    filenames.append(os.path.join(root, file))

        #Calculate the total time of all videos in folder
        totalTimeInSeconds = 0
        print "Calculating video lengths..."
        for file in filenames:
            # Calculate total time
            lengthInSeconds = videoLength(file)
            totalTimeInSeconds += lengthInSeconds

        hours = int(totalTimeInSeconds / 3600)
        minutes = int((totalTimeInSeconds - (hours * 3600)) / 60)
        print "hours:", hours, "Minutes:", minutes
    else:
        print "Error: No folder found with path:", path

# Parse the plist format from mdls command on Terminal
# @return the time in seconds
# mdls -plist - filename.mp4
def videoLength(filename):

    myCommand = "mdls -plist - "
    myCommand = myCommand + "\"" + filename + "\""

    status, plistInput = commands.getstatusoutput(myCommand)

    videoLength = 0
    searchTerm = "<key data-preserve-html-node="true">kMDItemDurationSeconds</key>"

    # 1. find "<key data-preserve-html-node="true">kMDItemDurationSeconds</key>"
    # 2. grab text until next </real>

    realStart = "<real data-preserve-html-node="true">"
    realEnd = "</real>"

    index = plistInput.find(searchTerm)

    # Offset by length of search term
    startIndex = index + len(searchTerm)

    # Calculate new start/end positions
    startIndex = plistInput.find(realStart, startIndex)
    endIndex = plistInput.find(realEnd, startIndex)

    #offset start by length of realStart text
    startIndex += len(realStart)

    if startIndex != -1 and endIndex != -1:
        #Split and parse as number
        numberString = plistInput[startIndex:endIndex]
        numberString = numberString.strip()
        videoLength = float(numberString)
    else:
        print
    return videoLength

# Run the main method
main()

Connect