Monthly Archives: January 2022

Setting up swift on Ubuntu 20.04

This is an update to Setting up swift on Ubuntu 18.04 – installing Swift on Ubuntu 20.04.

Check out Downloads for the current info. from swift.org.

  • We need to install dependencies, so start with
    apt-get install binutils git gnupg2 libc6-dev libcurl4 libedit2 libgcc-9-dev libpython2.7 libsqlite3-0 libstdc++-9-dev libxml2 libz3-dev pkg-config tzdata uuid-dev zlib1g-dev
    
  • Next we need to download the tar for the version of Swift you’re targeting, mine’s Swift 5.5.2
    wget https://download.swift.org/swift-5.5.2-release/ubuntu2004/swift-5.5.2-RELEASE/swift-5.5.2-RELEASE-ubuntu20.04.tar.gz
    

Next up we should verify this download

  • First download the signature using
    wget https://swift.org/builds/swift-5.5.2-release/ubuntu2004/swift-5.5.2-RELEASE/swift-5.5.2-RELEASE-ubuntu20.04.tar.gz.sig
    
  • Now import the key
    wget -q -O - https://swift.org/keys/all-keys.asc | gpg --import -
    
  • Now run the following
    gpg --keyserver hkp://keyserver.ubuntu.com --refresh-keys Swift
    gpg --verify swift-5.5.2-RELEASE-ubuntu20.04.tar.gz.sig
    

Assuming everything’s verified we now want to extract the download into our preferred location – in my case I am just creating a folder name ~/Swift and extracting the tar to this location, running the following from this location

tar xzf swift-5.5.2-RELEASE-ubuntu20.04.tar.gz

Finally let’s update the path – I’ve added this to the last line of my .bashrc

export PATH=~/Swift/swift-5.5.2-RELEASE-ubuntu20.04/usr/bin:"${PATH}"

Struct, Class and now Record types in C#

I thought it’d be interesting to compare the three C# types, struct, class and record. I’m sure we all know that a struct is a value type and a class a reference type, but what’s a record.

The record “keyword defines a reference type that has built-in functionality for encapsulating data” (see Records (C# reference)).

Before we get into record. let’s review what struct and classes give us using the example of a Person type which has a FirstName property.

struct

struct Person
{
  public string FirstName { get; set; }
}
  • A struct extends System.ValueType and structs are “allocated either on the stack or inline in containing types and deallocated when the stack unwinds or when their containing type gets deallocated. Therefore, allocations and deallocations of value types are in general cheaper than allocations and deallocations of reference types.” See Choosing Between Class and Struct.
  • ToString() will output YouNameSpace.Person by default.
  • Structs cannot be derived from anything else (although they can implement interfaces).
  • Structs should be used instead of classes where instances are small and short-lived or are commonly embedded in other objects.
  • As structs are ValueTypes they are boxed or cast to a reference type or one of the interfaces then implement.
  • As a function of being a ValueType, structs are passed by value

class

class Person
{
  public string FirstName { get; set; }
}
  • A class extends System.Object and classes are reference types and allocated on the heap.
  • ToString() will output YouNameSpace.Person by default.
  • Obviously classes may extend other class but cannot extend a record and vice versa, records cannot extend classes.
  • Reference types are passed by reference.

record

Records can have properties supplied via the constructor and the compiler turns these into readonly properties. The syntax is similar to TypeScript in that we can declare the properties in a terse syntax, such as

record Person(string FirstName);

Whilst records are primarily aimed at being immutable we can still declare them with mutability, i.e.

class Person
{
  public string FirstName { get; set; }
}
  • Records can only inherit for other records, for example
    record Scooby() : PersonRecord("Scooby");
    
  • Records use value comparison (not reference comparison) via IEquatable
  • ToString formats output to show the property values
  • Records support the with keyword which allows us to create a copy of a record and mutate at the point of copying. Obviously as records are generally aimed at being immutable this use of with allows us to copy an existing record with some changes, for example
    var p = somePerson with { FirstName = "Scrappy" };
    

    This is not a great example with our record which has a single property, but if we assume Person also had a LastName property set to “Doo” then we’d essentially have created a new record with the same LastName but now with the new FirstName of “Scrappy”.

    We can also copy whole records by not supplying any values within the { } i.e.

    var p = somePerson with { };
    

Secure storage using Xamarin Essentials

In my post Fingerprint and biometrics authentication in Xamarin Forms I looked at using biometrics (face id/touch id) to authenticate a user.

Using biometrics is pretty useful, but ultimately we’d usually want to use the biometrics along with some way of storing a token, password or whatever. In other words the usual pattern would be something like this

  • Request the user login details and then ask if the user wishes to use biometrics to log into your application (as this post is about using biometrics etc. let’s assume the user does indeed want to use biometrics)
  • Store the token or other details for the successful login within secure storage
  • When the user next try to log into your application, offer an option to use the password to login but by default give an option to login via biometrics
  • Assuming the user selects biometrics, then use the previously show code for biometric authorisations
  • Upon success of the biometrics authorisation, get the token/password etc. from the secure storage and use that to connect to your application/service

So how do we use secure storage within Xamarin forms. The Xamarin Essential nuget package give us SetAsync, for example

await Xamarin.Essentials.SecureStorage.SetAsync(key, token);

and to read back from the storage we use GetAsync, for example

var token = Xamarin.Essentials.SecureStorage.GetAsync(key);

Awk Basics

I’ve been meaning to learn Awk for so many years – this post is just going to cover some basics to getting started for a proper read, check out The GNU Awk User’s Guide.

Note: I’m going to be using Gnu Awk (gawk) as that’s what’s installed by default with my machine, we still type awk to use it. So the commands and programs in this post should still all work on other Awk implementations for the most part.

What is Awk (elevator pitch)

Awk (Aho, Weinberger, Kernighan (Pattern Scanning Language)) is a program and simple programming language for processing data within files. It’s particularly useful for extracting and processing records from files with delimited data.

Example data

Before we get started, this is an example of very simple data file that we’ll use for some of the sample commands – this file is named test1.txt, hence you’ll see this in the sample commands.

One     1
Two     2
Three   3
Four    4
Five    5
Six     6
Seven   7
Eight   8
Nine    9
Ten     10

Running Awk

We run awk from the command line by either supplying all the commands via your terminal or by create files for our commands. The run the command(s) via the terminal just use

awk '{ print }' test1.txt

We can also create files with our awk commands (we’ll use .awk as the file extension) and run them like this (from your terminal)

awk -f sample.awk test1.txt

where our sample.awk file looks like this

{ print }

Awk, like most *nix commands will also take input via the terminal, so if you run the next command you’ll see Awk is waiting for input. Each line you type in the terminal will be processed and output to the screen. Ctrl+D effectively tells Awk you’ve finished your input and at this point the application exits correctly, so if you have any code that runs on completion (we’ll discuss start up and clean up code later), then Awk will correctly process that completion code.

awk '{print}'

Again, standard for *nix commands you can ofcourse pipe from other commands into Awk, so let’s list the directory and let Awk process that data using something like this

ls -l | awk '{ print ">>> " $0 }'

The $0 is discussed in Basic Syntax but to save you checking, it outputs the whole row/record. Hence this code takes ls listing the files in the directory in tabular format, then Awk simply prepends >>> to each row from ls

Basic Syntax

The basic syntax for an awk program is

pattern { action }

So let’s use a grep like pattern match by locating the row in this file that contains the word Nine

awk '/Nine/ { print $0 }' test1.txt

The / indicates a regular expression pattern search. So in this case we’re matching on the word Nine and then the action prints the record/line from the file that contains the expression. $0 basically stands for the variable (if you like) representing the current line (i.e. in this case the matching line). The final argument in this command is ofcourse the data file we’re using awk against. So this example is similar to grep Nine test1.txt.

Actually we can reduce this particular command to

awk '/Nine/' test1.txt

The pattern matching is case sensitive, so we could write the following to ignore case

awk 'tolower($0) ~ /nine/' test1.txt
# or
awk 'BEGIN{IGNORECASE=1} /nine/' test1.txt

In the first example we convert the current record to lower case then use ~ to indicate that we’re trying to match using the pattern matching/regular expression. The second example simple disables case sensitivity.

Awk doesn’t require that we just use pattern matching, we can write Awk language programs, so for example let’s look for any record with a double digit number in the second column (i.e. 10)

awk 'length($2) == 2' test1.txt

As you can see from the above code, we’re using a built-in function length to help us, check out 9.1 Built-in Functions for information on the built-in functions. As you can imagine we have string manipulation functions, numeric functions etc.

Start up and clean up

We can have code run at start of and at the end (or clean up) of an awk program. So for example

awk 'BEGIN {print "start"} { print } END {print "complete"}' test1.txt

In this case we simply display “start” followed by the lines from the file ending with “complete”.

Variables/State

As, I’m sure you’re aware by now, Awk is really a fairly fully fledged programming language. With this in mind you might be wondering if we can store variables in our Awk programs and the answer is yes. Here’s an example (I’ve formatted the code as it’s stored in a file and thus makes it more readable)

BEGIN { 
    count = $2 
}

count += $2 

END { 
    print "Total " count
}

I’m sure it’s obvious from the code, but I’ll go through it anyway – at the start of the application we initialise the count variable to the first row, second column value (in our test1.txt file this is 1) then when Awk processes each subsequent row we simply add to the count and update that until the end where we output the count variable.

Change the colour of the status bar on iOS (in Xamarin Forms)

As per my previous post Change the colour of the status bar on Android (in Xamarin Forms) we might wish to change the status bar on iOS.

Open Info.plist in a code editor and add the following (if it does not already exist)

<key>UIStatusBarStyle</key>
<string>UIStatusBarStyleLightContent</string>
<key>UIViewControllerBasedStatusBarAppearance</key>
<false/>

Basically we’re disabling the status bar from taking it’s appearance from the preferred style of the current view controller – see UIViewControllerBasedStatusBarAppearance.

Swift enumerations

Swift enumerations are similar like Java enum types in that they can declare functionality as well as the usual values.

To declare a basic enumeration we use the following syntax

enum Color {
  case red
  case white
  case blue
  // ... etc.
}

We can also declare using associated values, i.e.

enum Color: Int {
  case red = 1
  case white
  case blue
  // ... etc.
}

We can also declare enums as strings, for example

enum Color: String {
  case red = "Red"
  case white = "White"
  case blue = "Blue"
  // ... etc.
}

Enums can also have methods, so for example (a rather contrived example)

enum Color {
  case red
  case white
  case blue
  // ... etc.

  func isRed() -> Bool {
    self == .red // .red shows abbreviated syntax
  }    
}

We can also declare enum cases with associated data/properties, so for example

enum Device {
  case phone(model: String)
  case tablet(model: String)
  case desktop(model: String)
}

let device = Device.phone("Samsung")

switch device {
  case .phone(let model)
    print("Phone: \(model)")
  case .tablet(let model)
    print("Tablet: \(model)")
  case .desktop(let model)
    print("Desktop: \(model)")
}

Recursive enum, where we might refer to the enum within the enum require the use of the keyword indirectcase. for example

enum Thing {
  case value(String)
   indirectcase thing(Thing)
}

Swift basics – let’s try this again

A while back I looked into the Swift programming language but had so many other things on at the time that I didn’t get far with it, so let’s try again but from the basics.

This post is the equivalent of a cheat sheet of the basics of Swift.

Note: ofcourse there’s no way I could include everything about a language in a single post, so this in non-exhaustive and primarily aimed at understanding key points of the language to get us up and running quickly.

What are the absolute basics I need to know about Swift?

  • Swift does not require semi-colons at the end of lines unless a single line has multiple statements
  • We declare variables using the var keyword and const values use let and we can either supply type annotation if we want to be explicit about the type used (which we need to do if declaring a float as double is implicitly used if decimal point numbers are used), for example
    var a: Int = 1  // variable, explicit type
    var b = 1       // variable, implicit type
    let s = "Hello" // constant, implicit type
    let dbl = 42.9  // constant double, implicit type
    let fl: Float = 42.9  // constant float, requires explicit type
    

    Interestingly constants in Swift (using the let keyword) are evaluated at runtime, unlike some other languages, hence they can be assigned at runtime.

  • Nulls exist within Swift, but they’re known as nil
  • Like other languages, We can declare numbers as hexadecimal , binary etc. For example
    let million = 1_000_000
    let binary = 0b1010
    let oct = 0o52
    let hex = 0x2a
    
  • We can also declare variables using the types initialization methods, for example
    let a = Double(42)
    let b = Int(1.2)
    let c = Int("123")
    

    In the above b is equivalent to Int(round(1.2)) and c attempts to convert the string to an Int.

  • Type aliasing can be used to declare an alias to a type, which is useful for more complex types or just to give a type some context to it’s usage, for example
    typealias counter = Int
    typealias Predicate = (s: String) -> Bool
    
  • Int, Bool, Double and other such types are value types, meaning they’re passed by value, however unlike some other languages, String, Array and Dictionary are also passed by value. Swift uses copy on write (COW) to ensure that when we pass around an array (for example) it’s actually a copy of the reference until the time that it’s mutated, then a copy is made.
  • The usual operators, -,+,/,*,% as well as += etc. exist but there is no ++ or — in the latest version of Swift. Hence we instead use += 1 and -= 1 in it’s place
  • The standard ==, !=, <, >, <=, >= comparison operators exist as do the logical operators || and &&
  • Ternary operators (as per C++/C# etc.) exists so we can write
    let a = b > 0 ? "+ve" : "-ve or zero"
    
  • Parenthesis are not used around control flow i.e.
    if a > 0 {
    }
    

Value and Reference Types

As mentioned above, many types are value types in Swift, these include structures, enumerations and tuples as well as the basic types, Int, Bool etc. which is probably expected, however Array, Dictionary and Set are also value types which might not be expected.

Classes are reference types, and just like many other languages – the big difference between value and reference types is how they’re passed between functions.

Value types are passed by passing a copy of the instance (in other words any changes made are not reflected in the calling code reference). Reference types are passed by reference and hence changes to the instance are reflected in the original instance.

Swift uses COW (copy on write) for assignment of value type instances, however not all value types get this.

Conventions

I always believe that when you write code in different languages you should try to write in the conventions and idioms of that languages.

  • Classes, structs etc. should use PascalCase (also known as CapitalizedCamelCase)
  • Variables, constants, function/method names should use camelCase (also known as uncapitalizedCamelCase)
  • The preference is for curly braces not be on a line of their own except the last brace, in other words
    if a > 0 {
    } else {
    }
    
    // is preferred over
    
    if a > 0
    {
    }
    else
    {
    }
    
  • Instead of naming functions like this addItem a preference seems to be, where appropriate, to instead use a more generic name which the parameter name giving more information, i.e. add(item: String) – we’ll look at functions soon.

Comments

Single line comments start with // and block comments /* */, one difference to some other languages is we can also nest block comments, for example /* /* */ */

nil and Optionals

As mentioned earlier nil is the Swift equivalent of NULL, null etc. Swift has optionals (or nullables) which also extend to the String type, hence the syntax String? means String is optional/nullable and we therefor also have syntax such as the following to ensure person is not nil

let fn = person?.firstName

To unwrap an optional we use !, i.e.

if person.firstName != nil {
  let fn = person.firstName! 
}

Swift also include the nil coalescing operator f

let a = b ?? c

Arrays

Arrays are declared using fairly standard [] syntax, i.e.

let a = [21, 22, 23] 
let c = a + [45, 46] // concat the two arrays

Dictionary

Dictionaries can be declare using a key/value array syntax, i.e.

let d = ["A": "1", "B", "2"]
let empty = [:] // empty dictionary

Set

Sets are simply unordered arrays in essence so can be declared using the same syntax but we need to supply an explicit type to Swift, for example

let s: Set = [1, 2]

Strings

A string is a struct, hence passed by value and uses standard string syntax as per this example “Hello” but also a character is a single string value, i.e. “a”.

String interpolation uses the \(…) syntax, for example

let s = "\(count) items"

Tuples

Most languages seem to include a Tuple type, Swift is no different, we declare a tuple like this

let t1 = (1, "One")

and as we’re not using named parameters, access to the values in the tuple are accessed via

let n = t1.0
let s = t1.1

Alternatively we can declare the tuple with named params, i.e.

let t1 = (idx: 1, name: "One")

Now we can access via the names, i.e.

let n = t1.idx
let s = t1.name

Switch statements

Switch statement are very similar to C# etc. except they do not (be default) fall-through to the next case statement, hence break is only needed where we need to exit a case block before the end. The default case is also not a requirement like it is for exhaustive switch statements.

Let’s look at some examples

switch color {
  case "red":
    print("it's red")  
  default:
    print("not red")
}

We can also use compound cases, i.e.

switch color {
  case "red", "white", "blue": 
    print("it's red, white or blue")  
  default:
    print("not red, white or blue")
}

For integers we can also use ranges do switch on, for example

case 0...<10:
  print("less than ten")
case 10...20:
  print("between 10 and 20")

We can extend this further using the where keyword, for example if a value is within a range of values and where it also matches another predicate

switch a {
  case 0...10 where a % 2 == 0
    print("Event num between 0 and 10")
}

Tuple matching exists where we can match all parameters or some, using a discard to ignore a parameter, for example

[code language="csharp"]
let t = (0, 2)
switch t {
  case (0, 0):
    // do something
  case (0, _):
    // only care about first item
  case (_, 0):
    // only care about second item
}

Next up, we can value bind a tuple within the case clause, basically meaning we have a way to get the actual value and assign it as part of the matching process, i.e.

let t = (0, 2)
switch t {
  case (0, 0):
    // do something
  case (let x, _):
    // get's the first item assigns as x
}

So in the above we actual switch on a (0, 0) tuple pattern but then for any other we just assign the first parameter to x and discard the second.

I mentioned that break is used in some case, for example

switch a {
  case (let a) where a % 2 == 0
    if(a == 4) {
      break
    }

    print("Even number between 0 and 10 but not 4")
}

On the other hand, if we actually do want our cases to fall-through then we can use the fallthrough keyword, i.e.

switch a {
  case (let a) where a % 2 == 0
    print("Is even")
    fallthrough
  case 4
    print("Is 4")
}

Loops

We’ve seen earlier that ++ and — do not exist in Swift, so the C#/Java/C++ way of looping is not going to exist, instead Swift generally uses a syntax more in line with enumerables using ranges (denoted by startend to denote the start and end of a loop)

for i in 1...10 {
  print(i)
}

So this works rather like C# foreach, hence as you’d expect, we can iterate over array items and dictionaries using pretty much the same syntax, i.e.

let a = [1,10,200]

for i in a {
  // do something with i
}

With dictionaries we simply deconstruct the tuples of key/value like this

for (a, b) in dictionary {
  // do something with a and/or b
}

While loops also exist, and in these we will need to use the += or -= , for example

while i < 10 {
  i += 1
}

repeat {
  i += 1
} while i < 10

Functions

Functions are written in the form

func funtionName(arg: argType) -> returnType {   
}

So this means we’d write an add function like this

func add(a: Int, b: Int) -> Int {
  return a + b
}

Calling our add function requires that we supply the names of the parameters, so to call this function we’d use the following

add(a: 1, b: 2)

In some cases we’d prefer to have anonymous arguments, i.e. not requiring the developer to supply the names, this would require the named parameter to be prefixed by a discard, i.e.

func add(_ a: Int, _ b: Int) -> Int {
  return a + b
}

and now we can just supply the arguments by index, i.e.

add(1, 2)

Interestingly we can also declare function parameters with two names, for example

func data(for request: URLRequest) -> Srring {
   // do something
}

In this case the first name for is the external name, i.e. the caller uses, whereas the second name request is the name used internally within the actual function.

Default values for parameters are also supported, for example

function fn(s: String = "Hello") -> Void {
}

Variadic arguments can be used, only one parameter can be variadic however, unlike some languages where this must be the last parameter of a function, due to variable names being used, the variadic argument can be in any position, for example

func addThenMultiply(values: Int..., multiplier: Int) -> Int
{
  for v in values {
     // do something
  }

  return somevalue
}

and we can call this using the following

addThenMultiply(args: 1, 2, 10, multiplier: 9)

Many of the other standard syntax exists, such as function overloading, passing functions (which are first class objects in Swift) as arguments etc.

One interesting addition is the requirement to mark functions which change state as mutating, for example, assuming the following code was part of a Container class which changes the internal storage when we add items

mutating func add(item: MyClass) -> Void {
}

Guards

The guard keyword can be used for preconditions on a functions, for example

func doSomething(i: Int) -> Void {
  guard i >= 0 else {
    return 
  }

  print("Positive")
}

Closures

Swift supports closures and we can assign closures to variables like this

var c = { print("Inside Closure") }  // () -> Void
var d = { return 123 } // () -> Int

Swift comes with a special syntax for trailing closures whereby a function is passed into another function without the need to supply the parenthesis, for example if we have a function like this

func fn(f: () -> Int) -> Void {
}

We can ofcourse supply one of our previously defined closures like this

fn(f: d)

but we can also supply the closures as a trailing closure like this

fn {
  return 987
}

There’s an alternative syntax that allows us to access closure parameters using the parameter index, so for example

let op = (Int, Int)  -> Int = { return $0 + $1 }
// or shorthand version
let op = (Int, Int)  -> Int = { $0 + $1 }

Properties

We can declare properties on our types like this

protocol SomeType {
  var error: String { get set } // read/write
  var instance: String { get }  // readonly
}

Operator overloading

Operator overloading is supported, here’s an example

extention Math {
  static func +(lhs: Math, rhs: Math) -> lhs.value + rhs.value // assuming value exists on Math somewhere
}

We can also define custom operators, for example

extension Math {
  // prefix style op
  static prefix func -><- (value: Int) -> Math
}

// in use
let x = -><- 100

Structs, Classes, Protocols & Enums

I’m not going to spend too much time on these four types as they would take up a lot of space in this post (which is already long) but suffice to say we can create a struct, class, protocol and enum (an enum is more like the enums in Java than C# and is a type that may also include functionality). The syntax for each of these is pretty much as expected

struct MyStruct {
}

class MyClass {
}

enum MyEnum {
}

procotol MyProtocol {
}

A struct is a value type (as discussed previously) and can have properties, methods etc. Structs are heavily uses in Swift. A class is a reference type and as one would expect, can also have properties, methods etc. A protocol is similar to a C# interface bordering on an abstract type as it can contain default functionality.

Enums are able to have values (options) as well as functionality, so here’s a simply example

enum Color {
    case red
    case white
    case blue
    // ... etc.

    func isRed() -> Bool {
        self == .red // .red shows abbreviated syntax
    }    
}

Extensions

Swift also has the ability to create extension methods (as per C#). The extension method can be used on protocols, structs classes etc.

If you’re used to C# extension methods then you’ll know that they allow us to extend frameworks or other libraries (as well as our own) which methods without the need to change the actual types themselves. The syntax for Swift extension is as follows

extension String {
  func appendOne() -> String {
     return self + "1"
  }
}

Namespaces/Modules

It appears that Swift does not (in this current release) have a concept of namespace or modules (or at least not as namespace like units). So what do we do?

The most obvious way of duplicating a namespace (well to a point) is to host code within classes, structs or enums. In the case of a classes and structs we’d want to hide and make private the init()

@available(*, unavailable) private init() {}

With enums, if they do not contain cases then they cannot be instantiated, hence we can now just include the functions or whatever we want into an enum.

Exception handling

Swift uses a slightly different syntax to many other languages, it still has a try and a catch but the try does not wrap all code that may throw an exception. Exceptions in Swift are of type Error. So instead of wrapping code in a try block we wrap it in a do with try for specific lines, i.e.

do {
   let s = try getString()

   // do something with s
} catch MyError.StringError {
   print('String Error occurred')   
} catch MyError.SomeOtherError(let errorCode) {
   print('Some Other Error occurred, error code: \(errorCode)')   
} catch {
   print('Unhandled exception occurred \(error)')
}

In the above we declare our do block and our method getString potentially throws an error. We therefore try to call this method and if all is well, we’ll do something with the returns string. Otherwise we try to catch the error if it’s a MyError.StringError (some error we’ve previously declared in this case) otherwise the catch all takes care of things.

What might our StringError look like? Well as Swift loves it’s enums, we’d potentially declare custom error conditions like this

enum MyError: Error {
  case StringError
  case SomeOtherError(errorCode: Int)
}

Swift still uses the concept of throwing errors, so our method getString might look like this

func getString() throws -> String {
   throw MyError.StringError   
}

One neat feature Swift has around errors is that we can convert them to an optional, so for example

let s = try? getString()

In this case if getString throws and error it’s converted to a nil. If, on the other hand we know that the method will not throw an error, for example maybe it throws an error if some member variable has not been set and we know it has been set, then we can disable error propogation using

let s = try! getString()

Generics

This “Swift basics” has a lot of topics, I’ve tried to reduce down to bare minimum of functionality most developers would look for or expect within a language. One last one feature we’ll cover is generics.

As somebody who started using generics/templates way back in my C++ days and was surprised at the lack of them in Java and C# in their early days and even Go today (if I recall). It’s nice to see Swift has generics and uses the fairly standard syntax of <T> (well in some ways fairly standard), i.e.

func get<T>(index: Int) -> T {
   return someValue;  
}

Swift doesn’t have the concept of default(T) like C#, so instead we would use nil (Optional.None).

We can type constrain our generic parameters, for example if had an add method which should only work on MyClass types we would declare the method like this

mutating func add<T: MyClass>(item: T) -> Void {
}

Now, I said that Swift uses fairly standard syntax “well in some ways fairly standard”. The difference is when we declare protocols with, what’s called Associated Types. In the case of protocols we declare an associatedtype within the protocol, for example

protocol Container {
  associatedtype Item
  mutating func add(item: Item)
  func get(index: Int) -> Item
}

When we come to implement the protocol we declare the type via the typealias, for example

struct MyContainer: Container {
  typealias Item = MyClass

  mutating func add(item: Item) {
    // mutate something
  }

  get(index: Int) -> Item {
     // return something
  }
}

Ofcourse MyContainer itself might take generic parameters and hence we might have

struct MyContainer<T>: Container {
  typealias Item = T

And I think that’s more than enough for this post, other posts will probably focus more on specific parts of the language that are of interest.

Publishing a TypeScript package to NPM

Over the holidays I’ve been updating F# unit conversion code so that I can regenerate the unit converters for different languages/technologies, hence I now have F# unit conversion, one for C# (removes the dependency on FSharp lib and written more in a C# idiomatic way), then I created SwiftUnits for Swift and finally (for the moment) TypeScript named unit-conversions (I might look to rename in it keeping with the other libs).

So next up I wanted to get this code packaged and available via the preferred package manager, hence F# and C# are now on NuGet, Swift isn’t on a package site but can be used as a package via it’s github location, so finally I wanted to get the TypeScript code packaged and deployed to NPM and that’s what this post discusses…

Getting Started

  • First off you’ll need to have a NPM account, so if you’ve not got one, jump over to https://www.npmjs.com/ and create one.
  • Next, create a folder for your package and then run yarn init (or the npm equivalent) and tsc –init
  • Create an index.ts file in the same folder as your package.json – this will basically export all parts from our library to the user
  • Create src folder off of the root folder – this will contain the TypeScript source for our package/lib

We’ve got the barebones in place, now we can start to code and configure our package. Add the source for your package into the src folder and then in the index.ts file just export the parts you want, so for example src for my unit-conversions package contains the TS files (my library code) and the index.ts has exports from my src files, like this

export { Angle } from './src/Angle';
export { Area } from './src/Area';
// etc.

We’re not going to waste time looking at the source for this package as it’s available on github from the previously mentioned link.

package.json requirements

Let’s get to the package.json configuration. We’ll need a name for the package, now I wanted to use a namespace, hence my package name is @putridparrot/conversion-units. Next up we’ll need a version, I’m classing my code as a beta release, hence using 0.1.x where x is the latest build. You’ll usually give your package a description, keywords etc. Importantly we’ll need a main and typings entry to allow the developer using the package an entry point as well as TypeScripts typings/definitions.

Here’s my current package.json as an example

{
    "name": "@putridparrot/conversion-units",
    "version": "0.1.3",
    "description": "Units of measure converters package",
    "main": "dist/index.js",
    "typings": "dist/index.d.ts",
    "keywords": [
      "units",
      "conversion",
      "convert",
      "unit of measure"
    ],
    "repository": {
      "type": "git",
      "url": "https://github.com/putridparrot/unit-conversions"
    },
    "scripts": {
      "build": "tsc"
    },
    "devDependencies": {
      "typescript": "^4.1.3"
    },
    "author": "PutridParrot",
    "license": "MIT"
  }

In my case we’ll build the code to the output directory dist (so if you change this, often lib is used for example, you’ll need to change the folder in the main and typings entries of the package.json).

tsconfig.json

I’m just going to list the current tsconfig.json from my project below

{
  "compilerOptions": {
    "target": "es5",                          
    "module": "commonjs",                     
    "declaration": true,                      
    "outDir": "dist",                         
    "strict": true,                           
    "esModuleInterop": true,                  
    "skipLibCheck": true,                     
    "forceConsistentCasingInFileNames": true,  
    "rootDir": ".",
  },
  "exclude": ["node_modules", "dist"]
}

The above is a clean up version of the tsconfig.json that is generated via tsc –init but the basics are pretty obvious, the main additions I made were to explicitly state the outDir. Without this the generated JavaScript files will go into the src folder and we don’t want that. Also I added the rootDir and the exclude section. All should be pretty self-explanatory but if not, have a read of Intro to the TSConfig Reference.

Packaging

Assuming your code builds/transpiles using tsc then once that’s run we should have a dist folder with the .d.ts and .js files. Now it’s time to push this package to NPM.

From bash or your preferred terminal the following just to ensure you’re logged into NPM

npm whoami

If you’re not logged in or are logged into the wrong account (if you’re running multiple accounts) then run

npm login

Note: Remember if you’ve setup 2FA in NPM then you’ll be prompted to use your authorizer app. to supply the “one-time” pass code.

Now if you have a paid account you might publish a private package in which case just run

npm publish

But if you do not have a private package option or simply want to make the package public then simply run

npm publish --access public

You will get asked for the passcode again (if 2FA is enabled), but once supplied the package will become available on the NPM site.

If you also have the same code committed to github then you’ll probably have a README.md and this will also be uploaded and available on the package page of NPM.

Publish only what you need to

One thing you may find is that the publish command will actually publish pretty much everything to NPM (it automatically excludes node_modules and some other files, see The .npmignore File for information on what’s ignored by default).

This means that when you install a package to your application you’re getting all the files that make up that published package – so for example my initial published package include my .github folder.

As you can probably deduce from the link above, to filter out files/folders that you do not want/need as part of your published package, you can add the file .npmignore which basically takes the same format entries as .gitignore. So from this we might have something like this

tests
coverage
.github
src/

In this case I don’t want to publish the tests, coverage for github workflow. Also I remove the src as ultimately the package will simply use the dist/src anyway.

Using Powershell to get a file hash

If you want to check a get the hash for a file (for checking your downloads or generating the hash), you can use the following Powershell command

Get-FileHash .\yourfile.exe

In this example the default SHA256 algorithm is used against some file named yourfile.exe (in this example).

You can change the algorithm use by supply the -Algorithm switch with any of the following values SHA1, SHA256, SHA384, SHA512, MACTrippleDES, MD5 and RIPEMD160.