Posts tagged #swift

Swift - Cannot use += operator with String! from UITextField or UITextArea - Implicitly Unwrapped Optional

I'm guessing this is a bug (submitted bug #, but if it isn't, you'll be surprised to learn that in Xcode Version 6.1.1 you cannot append to a String from a UITextView or UITextField.

The problem is that both the UITextField and the UITextView are using an implicitly unwrapped optional String (String!) as the type. This is messing up the +=, so you either have to break apart the statement (defeating the purpose of +=). Or you have do a force unwrap before the +=.

If you don't you'll get a strange Swift Compiler Error stating that 'String!' is not identical to 'UInt8'

var numberString: String! = "0"
numberString = numberString + "2"

numberString! += "1"
numberString += "1" //'String!' is not identical to 'UInt8'

var textView = UITextView()
textView.text += "More text" //'String!' is not identical to 'UInt8'

var textField = UITextField()
textField.text += "Even more text" //'String!' is not identical to 'UInt8'
Posted on December 11, 2014 and filed under iOS 8, swift .

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

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

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 or read his Swift programming blog!

Connect

  • Do you have a story to tell? Email
  • Learn how to make apps with Swift.

Posted on November 3, 2014 and filed under Interview .

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 .