February 10, 2015

Swiftly Secure, Part 2 – Multiplying Huge Numbers

Posted in iPhone development, mac development tagged , , , , , , , at 12:11 am by tetontech

In my previous post I mentioned how two 64 bit numbers could be multiplied together without ever overflowing. The approach taken was a variation of the grade school multiplication algorithm. In this posting I continue my path to an implementation of the Socialist Millionaire protocol used to securely communicate between 2 or more peers. In order use socialist millionaire I will have to multiply numbers that are much too large to fit into a 64 bit integer. This means I’ll need to multiply arrays of numbers by arrays of numbers.

There are algorithms out there for doing multi-word multiplication. Warren, at hackers delight, lays out a C version of Knuth’s grade school algorithm. It works, but has a design point I was unwilling to follow. It requires the arrays being multiplied to consist of half-word numbers rather than full word numbers. I wanted to explore code using arrays of unsigned 64 bit numbers to represent the very long numbers. It seemed a waste to only use 32 bits per number.

With that in mind I sat down to figure out how to apply the multiplication algorithm used in the last post in this new situation. I wasn’t surprised when I found was easily adaptable from multiplying two Swift UInt64’s to multiplying two Swift UInt64 arrays (Please see the graphics and discussion in the previous post to understand the algorithm basics).

Part of the new algorithm implementation includes adding two UInt64’s in situations where they could readily overflow. That meant I needed to create an add method to handle this correctly. It isn’t that complicated but does require the use of bitwise operators and comparisons.

func add(leftAddend:UInt64, rightAddend:UInt64) 
                                ->(UInt64,UInt64){
    var carryAmount:UInt64 = 0
    let sum:UInt64 = 0
    //check for overflow
    if ~leftAddend < rightAddend{
        carryAmount = 1
        sum = rightAddend - ~leftAddend - 1
    }
    else{
       sum = rightAddend + leftAddend
    }
    return (carryAmount,sum)
}

This implementation of add checks to see if overflow will happen before doing the addition. If there is no danger of overflow the two addends are combined. If overflow will happen the amount of overflow is stored and the sum is set to the maximum value of a UInt64.

In either case the add function returns the sum and a number representing how much too large the real sum is if it was to fit into a UInt64. We’ll use this carry amount in the multi-word multiplication algorithm.

Another change I made from Warren’s implementation was to have the arrays of numbers be in big endian format. This didn’t add significantly to the complicatedness of the algorithm but is how people ‘normally’ think of numbers. This can make it easier for some to see how the input relates to the algorithm’s output.

If the algorithm is implemented correctly some simple multiplications and their results should match these below. All arrays of numbers are base 2^64 where each array element represents a 64 bit ‘digit’ in big endian bit order.

  • multiply([UInt64.max/2 + 1],[2])     => [1,0]
  •  multiply([1,0,0],[1,1])                          => [0,1,1,0,0]
  • multiply([2,2],[UInt64.max/2 + 1])  => [1,1,0]
  • multiply([UInt64.max, UInt64.max, UInt64.max], [UInt64.max, UInt64.max])          => [18446744073709551615, 18446744073709551615, 18446744073709551615, 18446744073709551615, 1]

In this implementation of the grade school algorithm discussed in the previous post the ‘bit’ size of the multiplicand and the multiplier are unknown. This means we can’t use the nice trick with the << operator and bit masks to create portions of the product we can add together. Instead we’ll collect the product portions directly into an array of UInt64’s.

If we create an array for the resultant product sized to be the sum of the sizes of the multiplicand and the multiplier it will always be large enough to hold the product. Sometimes it will be 1 digit too large but that will always be in the most significant digit location when it does happen. You can see an example of this if you look at the second bullet point of the list above. This is OK since a zero value in that place doesn’t affect the value of the number anyway.

The multi-word multiplication implementation of the algorithm looks like this.

func multiply(multiplicand:[UInt64], multiplier:[UInt64]) 
                                              ->[UInt64]{
    let multiplicandSize  = multiplicand.count
    let multiplierSize = multiplier.count
    let productSize = multiplicandSize + multiplierSize
    //create an array that is large enough 
    //to hold the product
    var product = [UInt64](count: productSize, 
                                         repeatedValue: 0)
    //follow the grade school methodology 
    //to do multiplication
    for index in stride(from: multiplierSize - 1, 
                                          to: -1, by: -1){
        let multiplierElement = multiplier[index]
        for subIndex in stride(from: multiplicandSize - 1, 
                                           to: -1, by: -1){
            let multiplicandElement = multiplicand[subIndex]
            //calculate the product and the carry amount
            let partialProduct:[UInt64] = 
        multiplyWithOverflow(multiplicandElement, multiplierElement)
            //calculate the location of the product
            let productIndex = (subIndex + index + 1)
            //calculate the index of the carry amount
            let carryIndex = productIndex - 1
            
            //calculate the amount to be inserted 
            //into the product and carry locations. 
            //Add the current calculated product to any amount that 
            //was previously carried forward.
            let (carryAmount, productSum) = add(product[productIndex], 
                                                    partialProduct[1])
            //the carrySum will never be able overflow.
            let (_, carrySum) = add(product[carryIndex], 
                                      carryAmount + partialProduct[0])
            product[carryIndex] = carrySum
            product[productIndex] = productSum
        }
    }
    return product
}

In this implementation each partial product is calculated and the overflow is placed in the next higher bit location. The partial product is then added to anything that was ‘carried’ over previously into the product’s location. For both the carryAmount and the partial product the add method described above was used to ensure overflows were handled correctly. While this algorithm isn’t quite as clean as the one in the last post, It is still fairly straight forward.

Since the socialist millionaire algorithm requires a division as one of its steps, my next posting will show an algorithm for multi-word division and subtraction. At this point, it looks like there will be some very interesting ideas to point out.

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.

Swift Arrays and Dictionaries with Various Types of Values using AnyObject

Posted in iPhone development, mac development tagged , , , , , at 7:25 pm by tetontech

Apple’s Swift documentation declares that Arrays and Dictionaries can only hold one type of value per collection. This is true but Apple’s examples are a little misleading. The code

var stArr:Array<String> = [“bob”,“sue”]

does create an Array named stArr that holds only strings. If you tried to add a number to stArr the code would fail to compile. The code

var anotherStrArr = [“sally”,“joe”]

would also create an Array that can only hold strings. An Array that can only hold Ints would be created from the code

var intArr = [4,56,7,12]

Whether the type is declared, as in the first example, or is the result of interpolation, as in the second and third example, only one type is storable in each of these Arrays.

What is not explained in Apple’s documentation is the use of AnyObject. The code

var interestingArray:Array<AnyObject> = [“sally”, “jones”, 45]

is not only legal, but it compiles and runs. Why?

Because all of the values in the array of of type AnyObject. An Array of AnyObjects can also be created by the interpolator.

var interpolatedInterestingArray = [“sally”“jones”, 45]

interestingArray and interpolatedInterestingArray will be identical in type and values. Understanding this isn’t particularly helpful if we restrict ourselves to Arrays. It can be very helpful when Dictionaries are being used. The code

var aPersonDictionary:<String,AnyObject> = [“firstName”:“sally”, “lastName”:“jones”, “age”:45]

is completely legal, creates a Swift Dictionary, and works well because all key-value pairs are of the same type: <String,AnyObject>. WARNING! The code

var interpolatedPersonDictionary = [“firstName”:“sally”“lastName”:“jones”“age”:45]

doesn’t yield the same result. Instead, the interpolator will assign a NSDictionary to the variable interpolatedPersonDictionary rather than a Swift Dictionary. This is important to know if you have a function that expects a Swift Dictionary. You can not directly pass an NSDictionary as a Swift Dictionary. They are not the same type.

My next post contains an operator and functions that need a Swift Dictionary using AnyObject rather than an interpolated NSDictionary.

June 13, 2014

Swift, WKWebView, and Calling from Swift to Javascript

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

Update: If you are interested in this topic you may find this new post helpful. It describes and updated version of the example code you see here and standardizes it for both Swift and Android.

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.

(Note: This code example has been updated for Swift 2.0 on my gitHub repository.)

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 8, 2014

Swift, Extensions, Single Value Tuples, Passing Closures, and Functional Programming

Posted in iPhone development, mac development tagged , , , , , , , , , , at 2:36 am by tetontech

Swift allows us to extend existing types. This is one of the features of Objective-C that I really like. Because existing types can be modified, I can add methods, and computed properties in the case of Swift, to instances of entities that have been created in a library other than my own. This would not be directly possible using the inheritance model since the library’s provider would not be able to instantiate objects of my sub-class.

That is a lot of verbiage. Let’s look at a specific case. Let’s say a JSON library returns me an Array and I would like that Array to have a new method. Using the inheritance model I would have to create a new instance of an Array subclass and then ensure all the elements of the initial array became part of the new instance. Not the fastest of options. A faster option would be to not sub-class Array but have the new instance of a class contain the Array. This would require creating methods of the new class to duplicate any needed Array methods. Also a non-optimal solution.

Swift’s extensions are a way to resolve this type of issue.  Below is a code example that adds methods to Swift’s Array class, and therefore all instances of Array regardless of their origin.

In the example I add two functional programming methods to Array. They are fold-left and fold-right. These are generalizations of Swift’s standard reduce method. Reduce always returns the same type as is found in the array. Foldl and foldr remove that limitation.

By including a file containing the following code in my swift application these two new functions become available for use on all Arrays.

import Foundation
extension Array{
	//U may or may not be the same type as the array elementsfunc foldl<U>(initial:U, combine:(U,T) -> U) -> U{

		if self.count > 0{

			var combined = initial

			let inverted = self.reverse()

			for index in 0..inverted.count{

				var element = inverted[index]

				combined = combine(combined, element)

			}

			return combined

		}

		return initial

	}
	//U may or may not be the same type as the array elementsfunc foldr<U>(initial:U, combine:(U,T) -> U) -> U{

		if self.count > 0{

			var combined = initial

			for element in self{

				combined = combine(combined, element)

			}

			return combined

		}

		return initial

	}

}

 

Some points to note. Both methods have footprints similar to Swift’s reduce method. This makes it easier to use and remember all three.

func foldl<U>(initial:U, combine:(U,T) -> U) -> U

Fold-left, foldl, is a generic function that uses two generic types;

  1. T – the type of the elements in the Array, and
  2. U – the type of the initial value with which the Array’s elements will be combined.

Foldl also has two parameters. The first is the initial element of type T. The second is a closure bound to the parameter name ‘combine’. This closure also has two parameters. These are found in a Tuple containing values of type U and of type T. The closure returns a value of type U. I have chosen to omit the parenthesis, (), around the U return type declaration since single value Tuples in Swift, such as (U), are compiled to values of the contained type, U, instead of Tuples. I have made this same decision regarding the return type declaration for foldl itself. I think it reduces the visual clutter.

For foldl and foldr to truly be functional methods they must not modify any value outside of themselves since this would violate functional programming’s no side effects rule. The ‘combine’ closure will enforce this rule since it will be unable to modify the Array using the keyword ‘self’. Self, if used in the closure, will not mean the Array being folded. In the example below these methods are called. In these closures ‘self’ would be a UIViewController since self would be captured from the closures environment.

override func viewDidLoad() {
        super.viewDidLoad()
        let b = [5,4,3,2,1]
        
        var result = b.foldl("Folding:", combine: {
            var aString = "\($0) \($1)"
            return aString
            })
        println(result)
        
        
        result = b.foldr("Folding:", combine: {
            var aString = "\($0) \($1)"
            return aString
            })
        println(result)
    }

Run results:

Folding: 1 2 3 4 5

Folding: 5 4 3 2 1

This is not generally the way you would want to build strings from Arrays in all conditions. Foldl and foldr do, however, make it possible to control the direction of iteration and allow you to compute a value of a type different than that contained by any Array. This new type could be a struct, an object, or anything else available to you in Swift.

Use reduce when appropriate but remember foldl and foldr for when you need them. For a more realistic example of the need for fold see the next blog posting.

June 5, 2014

Swift, tail recursion optimization, and looping

Posted in iPhone development, mac development tagged , , , at 5:18 pm by tetontech

Continuing my exploration of Swift I decided to try to see if Swift supported tail recursion optimization. To over simplify, a compiler can optimize a tail recursive function, one where the call to itself is part of the return statement of the function, to keep the application from failing due to the stack overflowing. The compiler does this by turning the recursive call into a loop. It ‘loopifys’ your recursive function since loops don’t push new function calls onto the stack.

Here is the Swift code I tried out. In it I call a function named recurse that pops the last element of of an Array and passes the reduced Array to itself again. The intent isn’t to calculate something useful, just to do tail recursion.

    func recurse(var aList:Array<Int>)->(){
        if aList.count == 0{
            return
        }
        aList.removeLast()
        return recurse(aList)
    }

I decided that 10,000 recursive calls would probably cause a stack overflow if the compiler didn’t optimize the recursion. You can play with that number to see if it was large enough. I also decided to test while and for loops to see if there was any significant speed differences between the approaches. I put the following code in a viewDidLoad method of my ViewController.

        var huge = Int[](count: 10_000, repeatedValue: 5)
        var clone = huge.copy()
        var recurseClone = huge.copy()
        
       //recursion
        var before:Double = NSDate.timeIntervalSinceReferenceDate()
        recurse(recurseClone)
        var diff:Double = NSDate.timeIntervalSinceReferenceDate() - before
        
        println("recurse milliseconds: \(diff * 1000)")

        before = NSDate.timeIntervalSinceReferenceDate()
        //while loop
        while clone.count > 0{
            clone.removeLast()
        }
        diff = NSDate.timeIntervalSinceReferenceDate() - before
        
        println("while loop milliseconds: \(diff * 1000)")

        before = NSDate.timeIntervalSinceReferenceDate()
        //for loop
        for ;huge.count > 0; huge.removeLast() {}
        diff = NSDate.timeIntervalSinceReferenceDate() - before
        println("for loop milliseconds: \(diff * 1000)")

 

There was a speed difference, maybe due to the optimizations being applied to the loop code, but I didn’t see it as significant. It appeared that most of the time was spent in modifying the array size, as I expected it would.

Here are the results I got on my 2011 macbook

    recurse milliseconds: 5031.8089723587
    while loop milliseconds: 4869.86601352692
    for loop milliseconds: 4389.14501667023

 

In my opinion the time difference is insignificant given the operation being performed.

June 4, 2014

Swift, iOS, Threading, and Grand Central Dispatch

Posted in iPhone development, mac development tagged , , , , at 5:02 pm by tetontech

This post focuses on how to use GCD in a Swift application for parallel processing. My previous post shows how to use swift with NSOperations to execute code in a background thread.

To keep things simple, I’ve put the example code in the viewDidLoad method of the view controller for the application.

override func viewDidLoad() {
        super.viewDidLoad()
        let priority = DISPATCH_QUEUE_PRIORITY_DEFAULT
        dispatch_async(dispatch_get_global_queue(priority, 0), { ()->() in
            println("gcd hello")
            dispatch_async(dispatch_get_main_queue(), {
                println("hello from UI thread executed as dispatch")
                })
            })
        println("hello from UI thread")
    }

Notice the setting of the priority constant. If you try to use DISPATCH_QUEUE_PRIORITY_DEFAULT in the call to dispatch_get_global_queue you will get a runtime error (error #45). It appears this may be due to DISPATCH_QUEUE_PRIORITY_DEFAULT being an NSNumber and Swift wants it to be some other type and isn’t interpolating and boxing/unboxing the value. If you set the priority constant the error goes away.

Also notice that in the closure being sent to the main queue I’ve left out the ‘()->() in’ portion of the closure. It isn’t required. Swift can infer this. You could leave it out of the closure sent to the global queue too. I did it both ways for example purposes only since Swift is so new.

June 3, 2014

Swift, iOS, and Threading

Posted in iPhone development, mac development tagged , , , , at 10:25 pm by tetontech

When learning a new language I usually follow the same pattern. I figure out how to do parallel processing, reflection, and build a few apps. Here is the beginning of my exploration of threading in Swift. I’m using NSOperations in this post and will look at GCD in a followup post.

Here are the steps:

  1. create a new swift file and inherit from NSOperation,
  2. override NSOperation’s main method,
  3. now create an instance of your new operation class,
  4. set the thread priority, and
  5. add it to an NSOperationQueue instance.

So far not different than Objective-C.

For this example I’m going to create a Sift class that inherits from NSOperation called BackgroundSillyness. Then I’ll use BackgroundSillyness in a Swift application’s ViewController viewDidLoad method.

Creating an instance of NSOperation:

    let queue = NSOperationQueue()

 

BackgroundSillyness.swift source

//import the Foundation library
import Foundation
//inherit from NSOperation
class BackGroundSillyness:NSOperation{
//override NSOperation's void main(void) method
 override func main() -> (){
       println("hello from background")
 }

So that is the class file. Now for the source from the ViewController. I’ll only include the source from the viewDidLoad method in order to keep things simple. You will recognize some of what is happening here if you are familiar with Objective-C.

ViewController.swift source

override func viewDidLoad() {
    super.viewDidLoad()
    // Create a new instance of BackGroundSillyness
    let backgroundOperation = BackGroundSillyness()
    /* I decided I wanted to figure out how to replace blocks with closures, 
    * soI set the completion block of the operation. 
    * 'hello' will now print outafter 'hello from background'.
    */ 
    queue.addOperation(backgroundOperation)
   //this is the default value, but if you don't set it you will get an error.
    backgroundOperation.threadPriority = 0
    backgroundOperation.completionBlock = {() -> () in 
        println("hello") 
    }
}

So there it is. All of the other properties of NSOperations can be set in the same way as the completion block. You can also leave out the ‘()->()  in’ portion of the closure if you want. Swift will infer the input and return types for you if you do.

When you run this, you may find that the background operation’s message is mixed up in the one printed out in the UI thread. It appears that Swift doesn’t queue up messages to the console. It isn’t a defect just something to be aware of. You could add a long running loop in the background operation’s main method if you would like to stop this from happening.

Now I’m off to figure out how to get Grand Central Dispatch (GCD) to work in Swift.

September 10, 2011

At Last!!!

Posted in Android Development, iPhone development tagged , , , , , , , , , , , , , , , at 10:29 pm by tetontech

At long last (big sigh of relief here by me) QuickConnectFamily 2.1 is finally available for download.  It involved a lot of work by many people and has come together well.  There are some big changes for both the iOS and Android platforms.  These enhancements and changes have been driven by requests from developers like you.

Both:

  • This one is BIG.  The JavaScript functions now exist inside the qc name space.  In other words where you would have used the handleRequest method it is now the qc.handleRequest method.  The old behavior is deprecated.
  • Another BIG one.  In order to make the Control Function code more readable and more easily comprehended for those new to the framework all Control Functions MUST return one of the following three values (see the documentation for more information):
    • qc.STACK_CONTINUE – This instructs the framework to execute the next control function in the stack.
    • qc.STACK_EXIT – This instructs the framework to terminate all further stack execution.
    • qc.WAIT_FOR_DATA – This instructs the framework that a call to database or remote data has been made or a call to device specific behavior such as showing a map, displaying the camera, email editor or other native behaviors.
  • Work has been done to improve the asynchronous call stability in the underlying framework.  (Thank you to the team at affinityAmp).
  • Miscellaneous bug fixes and enhancements.

Android:

  • Bug fixes
  • Expanded database support and fixes
  • A major rework of the underlying Android Java code to make it match the design changes in iOS.  This is in preparation for QC Plugins and some new features such as ‘window-in-window’ that will be part of the next release as a Plugin.  The ‘window-in-window’ code is in there now but not official until it is converted to a plugin and the same behavior is available for iOS.
  • Added a hybrid sqlite database example

iOS:

  • Bug fixes
  • Removed the native footer code since libraries for scrolling and others such as Sencha, JQTouch, etc. are now of good quality.
  • QC Family Hybrid Plugin API and design spec completed.  There is an example of how you can add to QC on your own.  If you thing these additions could be useful to others you are free to charge for them, or not, host them yourself, notify me and I will add them to the plugin list on the QC plugin site.  If you are willing to donate them to the QC community send them to me for review and I will put them into the git repository and list them on the QC plugin site.
  • Updated all the examples to use the new return values and the new qc name space.
Now that this is out I will be creating a Key/Value store for Android and presenting it at the next AnDevCon.  I’m also looking forward to adding Android build support back into the QC Hybrid build process so you can write your app once yet build and run it in the iOS simulator and the Android emulator with one click.
As always I hope this is helpful for you.  I enjoy working on QC and hope to be able to do so long into the future.  If you find any issues please let me know via the google group.
Lee

Next page

%d bloggers like this: