Filtering by Author: Paul Solt

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

  • Have you encountered a similar error message in Swift?
  • Subscribe to my mailing list and get a free Swift video course.
  • I'm teaching an online Swift iPhone app course.
Posted on November 2, 2014 and filed under Programming .

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 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 = "kMDItemDurationSeconds"

    # 1. find "kMDItemDurationSeconds"
    # 2. grab text until next 

    realStart = ""
    realEnd = ""

    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

  • Do you have a better approach?
  • Subscribe to my mailing list and get a free Swift video course.
  • I'm teaching an online Swift iPhone app course.
Posted on October 23, 2014 and filed under Tips, Programming .

App Design Course from Award Winning iPhone App Studio: Tapity

Languages iPhone app

I'm excited to share a new App Design Course from Jeremy Olson, who started Tapity. Their iPhone apps have been featured prominently on the App Store, and they get how to work it.

Making an app is more than just programming. Programming is a big part, but by itself it's not going to make your app successful. There's a process that goes into making an app – it starts with an idea.

When you have an idea for app you need to flesh it out, and that's where the new App Design Course can help you reflect and think about your idea.

App ideas need revision and iteration to make them better. If you want to develop an award winning app, you're going to have to start thinking like someone who's already successful.

\n","url":"/zlrIcrsaj2U","width":854,"height":480,"providerName":"YouTube","thumbnailUrl":"http://i.ytimg.com/vi/zlrIcrsaj2U/hqdefault.jpg","resolvedBy":"youtube"}" data-block-type="32" id="block-yui_3_17_2_1_1413393872293_37912">

The course that Jeremy launched is something that you can't find anywhere else. Not only does it have his expert advice from selling , but he's interviewed some of the leading experts on the App Store.

You'll also get to learn from Mark Kawano (Storehouse, former Apple UX Evangelist), Ellis Hamburger (The Verge), Rene Ritchie (iMore), and Marc Edwards (Bjango).

If you want to make a great app, you'll need to learn how to approach the entire process from idea to app marketing.

Signup today and get the launch sale deal.

-Paul

Posted on October 15, 2014 and filed under Design, App Marketing .