Using Swift in a Legacy Objective C Project

I started learning Swift this week. I ran into my first time consuming problem when I tried to import my legacy Objective C classes into my Swift code. There are lots of good instructions on how to accomplish this task.

how-to-call-objective-c-code-from-swift

Unfortunately, I skipped over the one comment that said to include Foundation.h into my Objective C code:

Without it, you will see a lot of Unknown type error messages (e.g.
/Users/melling/Dropbox/dev/ios/Clock/Clock/Number.h:13:30: Unknown type name ‘NSInteger’)


#import <Foundation/Foundation.h>

@interface Numbers : NSObject

@property(assign, nonatomic) NSInteger numericalValue;
@property(assign, nonatomic) NSInteger dictId;

@property(strong, nonatomic) NSString *arabic;
@end

First Swift Program

I wrote my first Swift program tonight. It simply puts a button on the screen and handles the click event. Everything is done in code. Code on Github: https://github.com/melling/swift/tree/master/CenteredAutoLayoutButton

The relevant functions are here:

 func addButton() {
        centeredButton = UIButton()
        centeredButton.setTitle("Am I centered?", forState: .Normal)
        centeredButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
        centeredButton.setTranslatesAutoresizingMaskIntoConstraints(false)
        centeredButton.addTarget(self, action: "pressed:", forControlEvents: .TouchUpInside)
        
        self.view.addSubview(centeredButton)
        
        var viewDictionary:Dictionary = ["centeredButton": centeredButton]
        
        let horizontal:[AnyObject]! = NSLayoutConstraint.constraintsWithVisualFormat("H:|-50-[centeredButton]-50-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewDictionary)
        
        let vertical:[AnyObject]! = NSLayoutConstraint.constraintsWithVisualFormat("V:|-100-[centeredButton]-100-|", options: NSLayoutFormatOptions(0), metrics: nil, views: viewDictionary)
        self.view.addConstraints(horizontal)
        self.view.addConstraints(vertical)
        
    }
    
    func pressed(sender: UIButton!) {
        var alertView = UIAlertView();
        alertView.addButtonWithTitle("Ok");
        alertView.title = "My Title";
        alertView.message = "Congratulations";
        alertView.show();
    }

Autoincrement insert-select on a non-autoincrement column

There are often times when you need to insert into an existing table that contains data with a unique numeric field. If you created the field as AUTOINCREMENT, everything is fine. However, in my case, I did not because I generate sqlite tables from my MySql database. So, I have many tables that look like this:

drop table concentration_card if exists;

create table concentration_card (
	card_id int not null default 0,
	/*
      ...
	*/
);

create unique index idx0 on concentration_card (card_id);

I came across this answer on StackOverFlow, which I used to solve my problem: http://stackoverflow.com/a/3127004/2122052

First we need the maximum value from the desired field:

select max(concentration_card); -- We don't need a +1 here because we increment in SELECT

Then set the initial @curRow value and create the insert-select query:

 --insert into concentration_card
  SELECT @curRow := @curRow + 1 as card_id, 0, p.dict_id, 
      p.dict_id, 'Verbs' as name, 0 as inactive,
      '' as comments, 6 as major_group_id
  FROM picture_dictionary p
  JOIN    (SELECT @curRow := 1526) r
  where p.word_group = 'Verbs'
   and p.`dict_id` not in (  
 select word1_id
 from concentration_card
 where name in ('Basic Verbs', 'Common Verbs')
 );

Simple Go Web Page (GET Method)

I wanted to give the Go language a try today for a simple web page that I needed. Unfortunately, I got tripped up when I placed an extra / at the end of my handler. Thought I would post the first working copy here before I go off and finish the page. Hopefully, no one else gets burned by that little mistake.

package main

/*
http://localhost:3000/summary?param1=one¶m2=two
*/
import (
   "fmt"
   "net/http"
)

func summaryHandler(w http.ResponseWriter, r *http.Request) {

   var header = `
    <head>
    <meta http-equiv="Content-Type" content=\"text/html; charset=utf-8">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"
    <script src="/js/myjs.js"></script>

    <link rel="stylesheet" href="/css/dictionary.css">
    </head>
`
    fmt.Fprint(w, header)
    fmt.Fprint(w, "<h1>Hello World: Simple Go Web Page</h1>")
    params := r.URL.Query()
    fmt.Fprint(w, r.URL)
    fmt.Fprint(w, params)
    param1 := params["param1"]
    param2 := params["param2"]

    fmt.Fprint(w, "<p>Param1=", param1, "</p>")
    fmt.Fprint(w, "<p>Param2=", param2, "</p>")
}

func setupWeb() {
    // Put static assets in the resources dir
    http.Handle("/", http.FileServer(http.Dir("resources")))
    // WARNING: "/summary/" will cause pain with the GET
    http.HandleFunc("/summary", summaryHandler)

    err := http.ListenAndServe("localhost:3000", nil)
    if err != nil {
        panic(err)
    }
}

func main() {
    setupWeb()
}