NewFiveFour | Blog | Portfolio


Swift: Classes and properties

You define a class with class somename {}, and variables and constants are defined with var and let, and they can take private, public, static modifiers.

If you have a uninitialised variables, var s:String, you must have init(s: String) { self.s = s }. Normally you initialise with let c = somename() but in this case you do somename(s:"hi"). And you acces the properties with c.s for example.

If you prefix a variable with lazy then you can do lazy var prop: String = { /* fetch it somehow */ }() and you’ll get that value back in future gets.

You can compute values, by putting get and set(variable) in a block prefixed with the type, type { get {...} set(var) {...} } :

class com {
    var yes = "yes"
    var y: [String] { // If you prefix this with `class` it will be static
        get {
            return [yes.lowercased(), yes.uppercased()]
        } set(t) {
            yes = t[0]
        }
    }
}
var comv = com()
print(comv.y)
comv.y = ["yeah?"]
print(comv.y)

If you just have return something in the block, that works for a get only computed value.

You can observe how values of set similarly, with willSet and didSet in a block after the declaration.

class observed {
    var c: Int = 0 {
        willSet(nv) {
            print("Setting \(nv)")
        }
        didSet {
            print("Finished setting")
        }
    }
}
observed().c = 4
swift

Swift: Optional, nil and null

You can wrap a normal variable, like a string etc, in an optional by adding an question mark to the type: var s:String? = "hi".

Even if you, or something else, sets this to nil (there is no null in swift) then your program won’t crash when you access s.

You can check this is nil or not via if s == nil { ... }. Note, s is stil is an optional. To unpack it, to access the string, use s!.

To automatically unpack it in an if loop, use let: if let u = s { print(u) }.

swift swift-optional

Swift: Basics

A constant is let pi = 3.14 and a variable is with var. And if you want to convert a int to a String, then String(45) will do it. Type information isn’t needed, but let pi:Float =... would work.

A list is created with ["a", "b", "c"], and a map is with ["a":"b"], and access is l[0] and l["a"] respectively. The type signature is [String] and [String:String] and an empty structure is [String:String](). Or [] and [:] if type can be infered.

Happily, you can add such in strings via "hello \(l["a"]) there"

You can use for to loop through lists or maps like for (k, v) in someMap {}. Switch statements don’t have breaks and you can do logic: switch somevar { case "a","b": ... case let x where x.hasSuffix("ah"):... }.

swift

Android: Get versionName or versionCode of an APK from the command line

You can use aapt in android’s build-tools directory of whatever build tools version you’re using.

You pass that tool the badging command, and then pass it the location of your APK.

Example:

$ANDROID_HOME/build-tools/24.0.2/aapt dump badging app/build/outputs/apk/app-release.apk

If you scroll through all the output, you can find the versionName and versionCode.

android android-aapt android-versionCode

Scala: Using Scala's Try utility as an alternative to Java's Try/Catch/Finally

Let’s recall this standard SQL query code with the standard Java-esq try/catch/finally:

try {
  stmt = conn.createStatement
  rs = stmt.executeQuery(sql)
  // Deal with result set
  somethingToReturn
} catch {
  case e: Exception => ...
} finally {
  if(stmt!=null) stmt.close
  if(rs!=null) rs.close  
}

With scala.util.{Try,Failure,Sucess} it would be:

var insert = Try({
  stmt = conn.createStatement
  rs = stmt.executeQuery(sql)
  // Deal with result set
  somethingToReturn
})
if(stmt!=null) stmt.close
if(rs!=null) rs.close  
insert match {
  case Success(s) => s
  case Failure(e) => ...
}

The Try block has our code that may throw an exception.

Then we perform the code that was in the finally block after that.

And then finally we match if the Try value is a success or failure.

We’ve done a few things:

  • The finally code is no longer indented
  • Fewer lines starting with } keyword
  • The code that returns or fails is at the end now

This arguable makes things more readable.

scala scala-try

Page 1 of 65
Next