October 14, 2014

Swift, Structs, and Data Storage/Retrieval with sqlite

Posted in Uncategorized at 8:52 pm by tetontech

A data storage and interaction problem exits in Swift. If someone uses structs instead of objects in an attempt to take a more functional approach in coding their application, CoreData won’t work. It only interacts with objects, not structs. While Apple may solve this in the future, that possibility doesn’t help us now. To resolve this issue I decided to create two libraries that would behave like an ORM (Object Relational Mapper) but work with structs (STRUM?).

The first library runs all interactions with sqlite3 on background threads so we don’t have to deal with threading. The sqlite3 interaction is SQL based and generates and uses prepared statements, transactions, and rollbacks. I call this first library SwiftlyDB and its source code is available on my github repository. It is MIT licensed and the main purpose of this posting is discussing its API. Later postings will cover Swift lessons learned during SwiftlyDB’s creation.

The second library, currently in the design stage, will work with structs much like any ORM works with objects. It will translate between the results returned by SwiftlyDB queries and create the appropriate structs. It will also generate the SQL required to store struct information using SwiftlyDB. This means that this second library, which I’m currently calling SwiftlyStore, will make it possible to safely store, update, retrieve, and delete from storage Swift structs in an intelligent and parallel way.

Now let’s get down to how to use SwiftlyDB. SwiftlyDB is functional, parallel, light weight (less than 350 lines of code), flexible, and easy to use. Its API consists of two structs, SwiftlyDb and DBAccessError, and four functions; setupSwiftly, discardSwiftly, swiftlyTransact, and swiftlyTransactAll. The first two functions setup and disconnect from a sqlite3 instance for you and the last two execute SQL.

To get started, use setupSwiftly to generate an instance of SwiftlyDB. You do this by passing it the name of an sqlite file. This example uses ‘test.sqlite.’

let (error,aSwiftlyDB) = setupSwiftly(“test.sqlite”)

If the sqlite file exists in your application’s bundle, setupSwiftly will copy it, only once, to your application’s documents directory so it can be used. If you choose not to ship a database with your app setupSwiftly will create the sqlite file in the documents directory for you. Either way, you end up with a usable sqlite database file for your app.

In the example line of code above, aSwiftlyDB is of type SwiftlyDB optional and error is of type DBAccessError optional. When your file is copied and the sqlite3 database is opened, error will be nil and aSwiftlyDB will not.

‘test.sqlite’ used in this example has only one table, the ‘dog’ table with id:text, age:integer, and height:double fields. To add a single dog use the swiftlyTransact function, swiftlyTransact(aSwiftlyDB:SwiftlyDB, sql:String, parameters:Array<Storable>?, resultHandler:(DBAccessError?, Any?) ->()).

The example below shows how to add a dog without using prepared statements which, by the way, is not usually a good idea. An SQL string is assembled to insert the dog and the string, aSwiftlyDB returned from the call to setupSwiftly, and a closure containing code to execute after the insertion is done are passed in as parameters. As is possible in Swift, the closure is placed after the closing parenthesis to aid in readability.

let insertString = "INSERT INTO dog VALUES (\"\(NSUUID.UUID().UUIDString)\", 5, 3.2)"
swiftlyTransact(aSwiftlyDB!, insertString, nil){(error:DBAccessError?, data:Any?) ->() in
    println("inserted")
    if let theErrorDescription = error?.description{
        println("oops. got an insertion error. \(theErrorDescription)")
        return
    }
    else{
        println("updated \(data!) records")
   }
}

After the insertion is done using the sqlite3 C library, the result of the insertion operation is passed to the resultHandler closure. In this case, the data parameter is a Int representing how many records were changed (1). I’ve shown some simple error handling made possible by having both an error and the transaction’s data as parameters to the resultHandler.

Now that data is in the database how do we get it out? A second call to swiftlyTransact will do that for us. In the code below, all of the dogs in the table are requested and printed to the console. You could present this to the user via your app’s user interface but I’m trying to keep the example simple.

let selectString = "SELECT * FROM dog"
swiftlyTransact(aSwiftlyDB!, selectString, nil){(error:DBAccessError?, data:Any?) ->() in
    println("selection")

    if let theErrorDescription = error?.errorDescription{
        println("oops. got a selection error. \(theErrorDescription)")
        return
    }
    else if let dogs = data as? Array<Dictionary<String,String>>{
        println("found \(dogs.count) in dogs")
        for dog in dogs{
            for fieldName in dog.keys{
                println("\t\(fieldName) : \(dog[fieldName]!)")
            }
       }
       println("done with dogs")
    }
}

swiftlyTransact also works well for single prepared statements. This example shows how to add a single dog like the previous insert example.

let preparedStatementString = "INSERT INTO dog VALUES (?,?,?)"
swiftlyTransact(aSwiftlyDB!, preparedStatementString, [NSUUID().UUIDString, 5, 3.2]){(error:DBAccessError?, data:Any?) ->() in
    println("inserted")
    if let theErrorDescription = error?.errorDescription{
        println("oops. got an insertion error. \(theErrorDescription)")
        return
    }
    else{
        println("updated \(data!) records")
    }
}

Any library that forced you to execute a function call for every SQL statement would be poorly designed. SwiftlyDB uses swiftlyTransactAll to fill the roll of executing ‘sql scripts’, swiftlyTransactAll(aSwiftlyDB:SwiftlyDB, tasks:Array<Dictionary<String,Array<Storable>?>>,resultHandler:((DBAccessError?, [Any]?) ->())?) -> ().

swiftlyTransactAll has three parameters, an instance of SwiftlyDB to work with, a list of tasks to do, and a closure to execute once the list of tasks is complete.

This example adds 10 random dogs to the dog table using swiftlyTransactAll.

var taskList = Array<Dictionary<String,Array<Storable>?>>()
for index in 0..<10{
    let parameters:Array<Storable>? = [NSUUID().UUIDString,Int(arc4random()%12),Double(arc4random()%100)/10]
    let aTask = [preparedStatementString:parameters]
    taskList.append(aTask)
}

swiftlyTransactAll(aSwiftlyDB!,taskList){(error:DBAccessError?, data:[AnyO]?) -> () in
    println("inserted")
    if let theErrorDescription = error?.description{
        println("oops. got an insertion error. \(theErrorDescription)")
        return
    }
    else{
        println("updated \(data!.count) records")
    }
}

The last function in the API closes the sqlite database for you and cleans up.

Example:

discardSwiftly(aSwiftlyDB)

So that’s it. The entire API. Most of the code exists in the SwiftlyDB.swift file, but one item of interest exists in the Storable.swift file. It would be good to limit the parameters to types of things that make database sense; Strings, Ints, and Doubles. To this end String, Int, and Double have been extended to implement a custom Storable protocol found in the Storable.swift file. This way types of things that don’t make database sense such as user interface elements, controllers, delegates, etc. can not be accidentally sent to one of the swiftlyTransact functions.

SwiftlyDB is available for your use. It is functional in nature. It handles sqlite database transactions and rollbacks for you. It executes all database interactions in parallel to your code and does this safely. Take it and use it in any way you want.

My next postings will look at Swift lessons learned as I implemented this library.

August 20, 2014

Swift, Extensions, Protocols, and Operator overloading

Posted in Uncategorized tagged , , , , , at 4:39 pm by tetontech

I’m working on a Swift matrix manipulation library. Since I want that library to be flexible enough to be used outside of my planned use, a simulation engine, it needs to be able to handle complex numbers. Swift doesn’t have representations for imaginary or complex numbers so I created one. You can get the source for the entire library at my gitHub repo. I call the library SwiftlyComplex. Regardless of why I created the library, there are some Swift programming concepts the library illustrates.

I wanted my representation of complex numbers to be able to have Int and Double type parts but not String or other invalid types. Swift’s implementation of Int and Double have no common base class so I could have done something silly with Swifts Any type and do a bunch of run-time checking or I could have overloaded all my functions to handle all possible combinations of Int and Double. Both of these are bad ideas. For example, if the complex number’s init function had two parameters, one of the real component and one for the imaginary, using the overloading idea I would need to create four init methods that do essentially the same thing, initialize the complex number’s properties. The overloading approach would also make it difficult to declare the complex number’s property types as well. Not a good approach.

So what I did instead was create a BaseNumeric protocol.

protocol BaseNumeric {
    func asDouble() -> Double
    func asInt() -> Int
}
extension Int:BaseNumeric {
    func asDouble() -> Double{
        return Double(self)
    }
    func asInt() -> Int{
    return self
    }
}
extension Double:BaseNumeric {
    func asDouble() -> Double{
        return self
    }
    func asInt() -> Int{
        return Int(self)
    }
}

As you can see, I used this protocol to extend both Int and Double. This allowed me to make one version of all of the complex number’s init and other functions. I also had BaseNumeric add a couple of helper functions to Int and Double to return Double and Int versions of the number. This reduced code duplication in my complex number representation.

BaseNumeric also needed to override the -, +, *, and / operators. They are all very similar. We’ll look at just the override for the – operator.

func - (lhs:BaseNumeric, rhs:BaseNumeric) -> BaseNumeric{
    if lhs is Double || rhs is Double {
        return lhs.asDouble() - rhs.asDouble()
    }
    else{
        return lhs.asInt() - rhs.asInt()
    }
}

This version of the – operator can be placed between two BaseNumeric values, be they Ints, Doubles, or some combination of those, and returns a BaseNumeric. The operator checks the type to see if either BaseNumeric is a Double. If at least one is, then the result is calculated as a Double. If not, the result is calculated and returned as an Int BaseNumeric.

With the BaseNumeric protocol extending both Int and Double, I could now create a struct to represent complex numbers. I called it Complex. Complex implements Swift’s standard Printable protocol so using println() is easy. Implementing Printable meant I needed to add a calculated property of type String called description.

Following this same pattern, I added two custom calculated properties for the common complex number calculations modulus and conjugate. While you may not be dealing with complex numbers yourself, calculated properties in your code will work the same way. They are declared as variables, the return type is declared, the calculation is done, and a value is returned.

import Foundation

struct Complex:Printable{
    var real:BaseNumeric
    var imaginary:BaseNumeric
    
    var description: String{
        return "\(self.real) + \(self.imaginary)i"
    }
    
    var modululus: Double{
        let squaredReal = real * real
        let squaredImaginary = imaginary * imaginary
        return sqrt((squaredImaginary + squaredReal).asDouble())
    }
    
    var conjugate: Complex{
        let inversImaginary = imaginary * -1
        return Complex(real: real, imaginary: inversImaginary)
    }
    
    func combine(rhs:Complex, combineBehavior:(BaseNumeric, BaseNumeric) -> BaseNumeric) -> Complex{
        
        var realPart = combineBehavior(self.real, rhs.real)
        var imaginaryPart = combineBehavior(self.imaginary, rhs.imaginary)
        return Complex(real: realPart, imaginary: imaginaryPart)
    }
}

I also added a combine function. This function allowed me to do both addition and subtraction of my Complex structs with one set of code rather than duplicate the code for both behaviors. To accomplish this, I needed to pass an instance of a Complex to combine with the ‘self’ instance, and a closure, called combineBehavior in the parameter list. The closure would either add or subtract the component pieces of the Complex structs depending on if I wanted addition or subtraction. Calling the combine function in an overloaded version of the + operator shows how to pass the closure.

func +(lhs: Complex, rhs: Complex) -> Complex{
    return lhs.combine(rhs, combineBehavior: {(leftValue:BaseNumeric,rightValue:BaseNumeric) -> BaseNumeric in
        return leftValue + rightValue
        })
}

Since + is defined by Swift as an infix operator, I didn’t need to declare it myself. For a discussion of overloading standard operators and creating custom operators please see my previous posting on that topic.

In addition to the + and – operators, I overloaded the  * and / operators for my Complex class. They calculate the multiplication and division of complex numbers directly since there is not common code between these operators that could be shared.

Now I can create complex numbers using the Complex structure.

     let first = Complex(real: -2, imaginary: 3)
     let second = Complex(real: 1.0, imaginary: 2.0)

and manipulate them using the overloaded operators.

     let difference = first - second
     println("difference: \(difference)")
        
     let product = first * second
     println("product: \(product)")
        
     let quotient = first / second
     println("quotient: \(quotient)")

This makes it much easier to create, manipulate, and display complex numbers.

July 15, 2014

Swift to JavaScript and JavaScript to Swift. A round trip.

Posted in Uncategorized tagged , , , , , at 9:12 pm by tetontech

In a previous post I showed how to make a call from JavaScript to Swift. Take a look there for a more in-depth discussion of the code to accomplish that data transfer. This example expands on what I did in that post by showing how to make a call from JavaScript to Swift, do a calculation, and then pass the results back to JavaScript. The source code is very similar. It uses one method, evaluateJavaScript(), of the WKWebView class that wasn’t available in Apple’s previous Swift beta.

In the view controller’s userContentController method we’ll need to have access to the WKWebView created in the viewDidLoad method. This requires the addition of a WKWebView attribute to the ViewController class. After trying a couple of experimental ideas I remembered the correct, Swifty way to do this. I couldn’t create the WebView on the same line as the attribute was declared since the initializer for the WKWebView isn’t as simple as adding some integer attribute (var someInt = 3). Instead the initializer needs a frame and a WKWebViewConfiguration. Because of this the WKWebView must be initialized in the viewDidLoad method (This may change if Apple adds a WKWebView to Interface Builder).

The Swift way to declare an attribute and initialize it in something other than an init method is to make the attribute optional using the ? operator.

class ViewController: UIViewController, WKScriptMessageHandler {
    
    var theWebView: WKWebView?
}

In the viewDidLoad method the WKWebView can now be created using the WKWebView function. Once theWebView has been set, the ! operator is needed to declare that we know theWebView attribute is not nil.

    override func viewDidLoad() {
        super.viewDidLoad()
        var path = NSBundle.mainBundle().pathForResource("index", 
                               ofType: "html")
        var url = NSURL(fileURLWithPath: path)
        var request = NSURLRequest(URL: url)

        var theConfiguration = WKWebViewConfiguration()
        theConfiguration.userContentController.addScriptMessageHandler(self, 
                                   name: "interOp")

        theWebView = WKWebView(frame: self.view.frame, 
                             configuration: theConfiguration)
        theWebView!.loadRequest(request)
        self.view.addSubview(theWebView)

    }

As in the previous example, the userContentController() method must be implemented to handle the messages captured by the script message handler that was added to theConfiguration. In this example the message’s body, the data sent from the JavaScript is interpreted as an NSDictionary since the JavaScript sends an associative array.

    func userContentController(userContentController: 
       WKUserContentController!,
       didReceiveScriptMessage message: WKScriptMessage!) {
        
        let sentData = message.body as NSDictionary
        let aCount:Int = Int(sentData["count"] as NSNumber)
        
        theWebView!.evaluateJavaScript("storeAndShow( \(aCount + 1) )", 
                                        completionHandler: nil)
    }

The other change to the previous example is the addition of the call to theWebView’s evaluateJavaScript method. It has two parameters; a string that is the Javascript to be executed, and a function or closure that will be notified once the JavaScript completes. In this example I don’t need to know when the JavaScript completes so I passed nil as the second parameter.

The javascript for this example is strait forward; an onclick listener function to send a message to the Swift message handler, and the storeAndShow function that the Swift code will call to send a message back to the JavaScript.

var count = 0

function sendCount(){
    var message = {"count":count}
    window.webkit.messageHandlers.interOp.postMessage(message)
}

function storeAndShow(updatedCount){
    count = updatedCount
    document.querySelector("#resultDisplay").innerHTML = count
}

For my own code I would send a Dictionary back to the JavaScript where it would be used as an associative array. I left that out of this example since I didn’t think it was necessary to show.

Overall, the interaction between Swift and Javascript using the WKWebView is more strait forward than using the old UIWebView. It is nice to have a JavaScript way to directly call to Swift. I also like the selection of JSON as the data transfer format for the JS to Swift communication. It reflects the decision I made to adopt that format for QCHybrid years ago. It would be better if the values in the dictionary knew their type so casting using the as operator wasn’t needed but I can live with it the way it is.

June 17, 2014

Swift, Pipelining, Function Arrays, and Operator Overloading

Posted in Uncategorized tagged , , , , , , , at 9:46 pm by tetontech

In a previous post I showed how to create a pipeline operator, |>, that allows chaining of functions, closures, and mixtures of functions and closures. This posting will overload the pipeline operator so it can be used in a related but different situation.

In functional programming there are known good patterns. Two of these are map and reduce. Reduce applies a single function to an array of values and returns a single value. Summing the values in an array of Ints would be a good example.

Map is similar. It also applies a single function to an array of values. It returns a new array containing one value for each value in the original array but the new array values have been modified by applying the function. An example would be to map a double process to the array [1,2,3] generating and returning the new array [2,4,6].

There is yet another pattern that is common in programming and I use it a lot . It is related to map and reduce. In this situation a single piece of data, be it a Dictionary, Array, Int, String, or any other type, is passed to a series of functions. I haven’t seen a specific name for this type of behavior so I refer to it as spindle (a play on words – fold, spindle, or mutilate).

An example situation that fits the spindle pattern is the validation and application of data received from a source such as a file, a server, the user, etc. In this example I’ll be doing something that is so common in programming that it can seem trivial; validating a user name and password, authenticating the user, and displaying the user interface appropriate for the user. To do this let’s pretend that the data to be validated has come to us as JSON and been converted into a Swift Dictionary having the structure ["uName":,"pWord":,"userRole":].

A few functions to apply in our example would be helpful. These consist of different portions of the validation, authentication, display process. In each function a Tuple is returned consisting of a Dictionary<String,AnyObject> and a String? (String optional) (see my previous post for an explanation of using AnyObject with Dictionaries). The String? is used by the overloaded pipeline operator for error detection and early process termination. The example functions are:

func checkUName(data:Dictionary<String, AnyObject>) 
              -> (Dictionary<String,AnyObject>, String?){  
    if let userNameOptional = data["userName"]? as? String{
            if countElements(userNameOptional.stringByTrimmingCharactersInSet(
                   NSCharacterSet.whitespaceAndNewlineCharacterSet())) > 0{
                return (data, nil)
            }
    }
    return (data, "missing user name")
}
        
func checkPWord(data:Dictionary<String,AnyObject>) 
            -> (Dictionary<String,AnyObject>, String?){
    if let passWordOptional = data["passWord"]? as? String{
        if countElements(passWordOptional.stringByTrimmingCharactersInSet(
                  NSCharacterSet.whitespaceAndNewlineCharacterSet())) > 0{
            return (data, nil)
        }
    }
    return (data, "missing password")
}
      
//var data declares the data Dictionary to be variable rather than fixed.
//This is still functional since data is a copy of 
//the original data Dictionary.  
func isUser(var data:Dictionary<String,AnyObject>) 
             -> (Dictionary<String,AnyObject>, String?){
    // place authentication code here.
    /*
    if authentication passes 
          return (data, nil)
          data["isLoggedIn"] = true
    else
    */
    return (data, "invalid user name or password")
}
        
func showRoleDisplay(data:Dictionary<String,AnyObject>) 
              -> (Dictionary<String,AnyObject>, String?){
    // based on data["userRole"] show a view that matches the users role.
    return (data, nil)
}

For this example we create an Array called login that represents the entire process by listing the functions in the order we want them executed.

var login = [checkUName, checkPWord, isUser, showRoleDisplay];

A Dictionary for use in our example is also created.

var user:Dictionary<String,AnyObject> = ["userName":"sue", 
                        "passWord":"gr4583rt!", "userRole":14]

Using the pipeline operator we will see below, the code to apply login to the user Dictionary is

let (aResult, errorMessage) = login|>user

This line of code reads “Let a tuple be assigned the result of attempting to login a user.” You could also think of it as “Apply login to user and assign the result to a Tuple.” Either way you view the line of code, it seems to read well due to the operator.

So what does the code for the overloaded pipeline operator, |>, look like?

Since we declared the operator in a previous post and are using the same project we do not need to redeclare the operator. The code to overload it is

1 func |> <T>(left: Array<(T) -> (T, String?)>, var right: T ) -> (T, String?){
2    for function in left{
3        let (partialResult,message) = function(right)
4        if message != nil{
5            return (partialResult, message)
6        }
7        right = partialResult
8    }
9    return (right, nil)
10}

Operators are functions so the first line includes the func keyword, the name of the operator, two parameters, and a return of a tuple that includes a String optional. The first parameter, left, is an Array of functions that accept any type T and return a Tuple consisting of that type T and a String optional. The second operator, right, is a variable of the same type T.

Line 2 of the operator iterates over each of the functions in the left parameter. Each function is then called on line 3 and its returned result is checked on line 4. If an error message has been received it, along with the object of type T, partialResult, is returned to break the loop and early terminate the execution of the array of functions.

Line 7 updates the result that will be passed to any subsequent functions called or returned as part of line 9.

This operator can also be used with closures since functions are named closures in Swift.

June 13, 2014

Swift, WKWebView, and Calling from Swift to Javascript

Posted in Uncategorized tagged , , , , at 7:34 pm by tetontech

In a previous post, I showed how to embed Apple’s new WKWebView using Swift to create a ‘full view’, hybrid JavaScript application. An ability that QC Hybrid and PhoneGap, both early hybrid development platforms, had was to allow calls to be made from Javascript down to the native language of the device. In the case of iOS that was, and can still be, Objective-C but now can also be done in Swift. The new WKWebView has new functionality available in both languages that requires much less overhead to accomplish this interoperability than the old iOS UIWebView and Android WebView. The WKWebView currently does have an important limitation I’ll discuss in a moment.

There are two parts needed to achieve iOS’s new interoperability; a ‘listener’ of type WKScriptMessageHandler on the Swift side and a new object that has a postMessage() method on the Javascript side. When the Javascript postMessage() method is passed an array, associative array, object, or other Javascript type, the postMessage() method will JSON what it was passed. It then pushes this JSON string as a message to a queue on the Swift side of the application. At this point the JSON is parsed and the message becomes the matching Swift types, Array, Dictionary, String, Int, Double, etc. Custom Javascript objects become Dictionaries. Now your code in the WKScriptMessageHandler’s didRecieveMessage() method has Swift objects without needing to use JSON libraries in either the Javascript or Swift portions of your code. This is great. Unfortunately, at the time of this posting, there is no matching functionality in the beta release to easily push Swift objects back up to Javascript. Hopefully this will come soon. If not, there will need to be some ‘hack-like’ work-arounds similar to what QC Hybrid and PhoneGap had to do. This would be unfortunate.

The source code for this posting’s example is a modification of the previous post’s source. Rather than repeat the discussion of those portions of the example I’d suggest you review the previous post about how to do the embedding. The example below is the contents of a ViewController.swift file. It includes the changes needed to setup JS -> Swift interoperability (JS->Objective-C would use the same classes and methods) for an iOS single view application. The changes can be seen in lines 4, 14-18, and 29 – 31.

Line 4 declares the ViewController class as conforming to the WKScriptMessageHandler protocol. Notice that unlike Objective-C, Swift protocol declarations look just like object inheritance calls (in this case ViewController inherits from UIViewController). Swift only allows single inheritance, like Java. When doing both inheritance and protocol declarations the inheritance declaration must come first. If no inheritance is being done then a protocol declaration can be the first item after the : operator.

1 import UIKit
2 import WebKit
3
4 class ViewController: UIViewController, WKScriptMessageHandler {
5    
6    override func viewDidLoad() {
7        super.viewDidLoad()
8        
9        //prepare
10        var path = NSBundle.mainBundle().pathForResource("index", 
                                        ofType: ".html")
11        var url = NSURL(fileURLWithPath:path)
12        var request = NSURLRequest(URL:url)
13        
14        //changes from last post
15        var theConfiguration = WKWebViewConfiguration()
16        theConfiguration.userContentController.addScriptMessageHandler(self, 
                                        name: "interOp")
17        var theWebView = WKWebView(frame:self.view.frame, 
                                        configuration: theConfiguration)
18        //end of changes
19        
20        theWebView.loadRequest(request)
21        self.view.addSubview(theWebView)
22    }
23
24    override func didReceiveMemoryWarning() {
25        super.didReceiveMemoryWarning()
26        // Dispose of any resources that can be recreated.
27    }
28    
29    func userContentController(userContentController: WKUserContentController!, didReceiveScriptMessage message: WKScriptMessage!){
30        println("got message: \(message.body)")
31    }
32
33 }

Line 15 introduces a new class, WKWebViewConfiguration. This class manages various types of configurations for any and all WKWebViews used in your applications. One of the WKWebViewConfiguration’s properties is a content controller named userContentController. This is the object we need to access in order to setup the ViewController class as the ‘listener’ for messages from Javascript.

Line 16 shows how to assign the ViewController to be the Javascript message handler for any messages generated as part of the named message queue ‘interOp’. You can select any name you want instead of interOp. It just sounded good to me.

Line 17 shows how to initialize the WKWebView with both a frame and the WKWebViewConfiguration instance. This tells the WKWebView to create an opportunity to use the Javascript postMessage() method.

We’re almost done. The only other change needed is to create the ‘listener’ method, userContentController.didRecieveScriptMessage(). One of the parameters to this method will be the WKScriptMessage generated as part of the interoperation between your JavaScript and Swift. The message has a property named body that is the Swift version of the JSON data passed from JavaScript. Line 30 shows this example printing the Swift objects that the example sends from the Javascript side.

I created a simple Javascript function in the project’s main.js file that you can see below. Notice the new window.webkit.messageHandlers object. It has an attribute ‘interOp’ that matches the name we used on line 16 of the Swift code. The JavaScript interOp object is the ViewController since it conforms to the WKScriptMessageHandler protocol and was assigned on line 16 with the interOp name.

function sendMessage(){
    var aMessage = {'command':'hello', data:[5,6,7,8,9]}
    window.webkit.messageHandlers.interOp.postMessage(aMessage)
}

That’s it. Now we can send any object, array, or primitive as a message to Swift. Hopefully Google will not re-invent the wheel when they add this same type of interoperability to Android. They should make their Javascript side look exactly this same way. There is some advantage to copying.

 

For an example of how to call from JavaScript to Swift and then back to JavaScript see this other post.

June 10, 2014

Swift Classes, Structs, Enums, and Tuples compared

Posted in Uncategorized tagged , , , , , , at 10:25 pm by tetontech

In Apple’s Swift book there is a chapter on Classes and Structs. The first major section of that chapter describes how Classes and Structs are the same and how they differ. There were a few things that they left out of the list. They also didn’t compare them to Enums and Tuples.

In this posting I’m going to display a table that compares all four types, but leaves out what Apple already has in their book. Including that information would clutter what I’m trying to get across. Please go look there to see more similarities and differences.

 

Classes

Structs

Enums

Tuples

size

includes sizeof elements includes sizeof elements

passing

by reference by value no passing by value

methods

can have can have can contain functions and closures

contained values

as properties as properties as constants as elements

calculated properties

supported supported no no

 

The size row is the result of observing the results of calling the C sizeof() function on classes structs and enums. Tuples can’t be passed to sizeof() so that result is deduced.

Enumerations are not passed. All the other types are passed by value or reference as shown in the table. The only variance from this rule is Arrays. As said in the book, they are passed by reference until, not unless, a modification to the Array is made that changes its length. Then a copy is made and you are dealing with a copy.

The methods  row has a blank in the Enum column. Enums can’t have methods but they can contained pre-built switches that can be accessed (See Apple’s Swift book for details).

Calculated properties are somewhat like methods that are accessed by a property name. There is no data storage, only a return from a method call.

There are more of these, such as subscript support, that I’ll be adding to this table as I explore further.

June 9, 2014

Swift, Functional Programing, Structs and Fold

Posted in Uncategorized tagged , , , , at 10:08 pm by tetontech

In the last post I gave a pretty lame example of how to use fold. It was assembling a string from an array of numbers. Since the emphasis of that post was the source code for foldl and foldr I thought a lame but simple example would be OK. In this post I’m giving a computationally more significant example.

Let’s say you have an bunch of gerbils you are tracking and you need to know how many males and females there are. To simulate data input and storage routines outside the scope of this example let’s generate a series of pseudo-random gerbils and put them in an Array for later use.

    /*
    * example setup code
    */
    var gerbils:Array<Gerbil> = []
        
    for index in 0...20{
        /*
        * arc4random returns a UInt32. Create an Int from it.
        */
        let anAge = Int(arc4random() % 5)
        let aSex = Int(arc4random() % 2)
        /*
        * use Swift's ternary operator to change the aSex
        */ integer into the representative string
        gerbils.append(Gerbil(age: anAge, sex: aSex == 1 ? "female" : "male"))
    }

    /*
     * Gerbil struct source
     */     
    struct Gerbil{
         var age:Int
         var sex:String
    }

Now let’s take this Array of Gerbil structs and find out how many males and females there are. Either foldl or foldr would work so lets pick foldl. Swift’s standard reduce method would not work since reduce would require a Gerbil to be returned when given an Array of Gerbils. That doesn’t make sense here nor does that restriction make sense in most situations. That’s why we need fold methods for the Array class (See the previous post for the fold source code).

In this example foldl is passed an initial countBySex struct called statsWrapup that has both the male and female counts set to zero. Selecting zero for initialization makes it easy to increment the values, using Int’s ++ operator, when we find a male or female Gerbil. This detection and incrementation is done using Swift’s Ternary operator ?:

        /*
         * example begins
         */
        var statsWrapup = gerbils.foldl(countBySex(males:0, females:0)){
            var (ageBySexTracker, aGerbil) = $0
            aGerbil.sex == "female" ? ageBySexTracker.females++ : 
                              ageBySexTracker.males++
            return ageBySexTracker
        }
        println("females: \(statsWrapup.females) males: \(statsWrapup.males)")

        /*
         * countBySexStruct source
         */
         struct countBySex{
            var males:Int
            var females:Int
        }

There are many other choices that could have been made for this example. The sex indicator could have been left an Int with 0 or 1 potential values, the sex indicator could have been a boolean value with true for female and false for male, an Enumeration could have been created and used as the sex indicator, etc. but I chose not to do this for example clarity and to focus on why fold needed to be used instead of reduce.

Could this have all been done using a standard for loop? Of course. But why should we make that choice. It will increase the ‘glue’ code in our application that is written repeatedly and used rarely. It is well known that each line of code we write is a new potential bug. One way to reduce the bugginess of code is to stop creating code that is rarely used. By wrapping the looping code into a pre-exiting function, such as map, reduce, or fold, we execute the code many times. This can aid and speed debugging.

April 15, 2014

Project ARA and the MDK

Posted in Uncategorized tagged , , , at 6:15 pm by tetontech

I am excited to see Google’s project ARA and its developer kit, the MDK. It sounds very interesting as a development platform for just about anything.

As I was reading through the license agreement I ran across this item.

“3.2.5 You agree not to enjoin in any way (including, without limitation, seeking or obtaining any cease and desist order or any importation exclusion order, or through enforcement of a court-ordered injunction) another party’s manufacture, use, sale, offer for sale, importation or distribution of modules that comply with the requirements of the MDK.”

It seems to me this precludes any enforcement of intellectual property rights involved with the production of a module. If I create something fantastic, someone else takes it apart, duplicates it exactly, and puts it into production I can not stop them. This certainly would stop the intellectual property wars but there may be an unanticipated consequence.

What incentive do I, as a startup or an existing large company, have to do major research and development if I can not recoup my investment? It seems that this may lead to a situation where most or all modules developed for ARA have a low upfront budget. While this doesn’t preclude dramatic innovations that lead to completely new ways of interacting with and creating computing devices, it seems to me that this limitation may reduce the probability of such innovations being being financially possible.

October 1, 2013

xCode 5 git and bitbucket

Posted in Uncategorized tagged , , at 7:21 pm by tetontech

I just was creating a new iOS project and needed to share it with a dev team. I wanted it private so I used bitbucket. 

 

Here is how I got git working from within xCode 5.

 

  1. I generated a new project and made sure I selected the option to create a local repository.
  2. I created a bitbucket project using their web interface.
  3. I opened the mac Terminal application.
  4. Here are the steps in Terminal:

Then I added a remote to xCode.

  1. Select: Source Control > projectname – Master > Configure projectname
  2. Click the Remotes selection at the top of the Configure window
  3. Click the + symbol in the bottom left of the window
  4. Select Add New Remote
  5. Add any name you prefer
  6. Paste in the https url used to add the remote (https://bitbucketusername@bitbucket.org/&#8230;.)
  7. Select Add remote

Then I did a commit

  1. Select Source Control > Commit
  2. Added an initial commit message to the bottom of the commit window

Last of all I did a push

  1. Select Source Control > Push

And now everything is all hooked up and working. I can add, change, and delete files and then do commits and pushes

 

January 30, 2012

Updates to Some Libraries

Posted in Uncategorized tagged , at 4:10 pm by tetontech

With changes that have been happening in my life, specifically going back to school to get a doctoral degree, I find that I am no longer able to support the full suite of QC libraries.  The QuickConnect Hybrid framework will now be the only one I am supporting.

When I am done with the degree I will again be supporting the other libraries.  There is only so much time in the day.

The other libraries, such as enterprise sync, QCJSON, QCNative, etc. are and will still be available for download from source forge.

 

Thank you,

 

Lee Barney

Next page

Follow

Get every new post delivered to your Inbox.

Join 318 other followers

%d bloggers like this: