A basic struct in iOS (Swift), Windows (C#), and Android (Java)

I'm not going to argue the pros and cons of structs here, I'm simply going to outline the basic code to make use of them across three platforms: iOS, Windows and Android.

iOS (Swift)

A struct can hold any type of object in Swift.

struct Paragraph {
    var text:[String]
    var level:Int
}

Implementation is as follows:

var myParagraph = Paragraph(text:["This is the first sentence in my paragraph.", "This is the second sentence in my paragraph."], level:1)

Access of properties:

var paragraphLevel = myParagraph.level

Windows (C#)

Windows also has a struct type, but the creation of structs in C# is closer to class creation and is less automated than it is in Swift.

public struct Paragraph
{
    public readonly string[] text;
    public readonly int level;
    public Paragraph(string [] text, int level)
   {
        this.text = text;
        this.level = level;
    }
}

Implementation is as follows:

String[] myStrings = {"This is the first sentence in my paragraph.", "This is the second sentence in my paragraph."};
Paragraph myParagraph = new Paragraph(myStrings, 1)

Access of properties:

int paragraphLevel = myParagraph.level

Note: in this example, I've used the readonly keyword to mirror the behaviour of Swift as closely as possible. For further usage of the struct in Windows, see here.

Android (Java)

Android doesn't have support for structs, so in order to repeat the behaviour of a basic struct (in Swift) as closely as possible we want the values to be set once at the time of creation and no longer be changeable. The following example is inspired by an approach from Stackoverflow.

class Paragraph {
    public final String[] text;
    public final int level;
    public Paragraph (String[] text, int level) {
        this.text=text;
        this.level=level;
    }
}

Implementation is as follows:

String[] myStrings = {"This is the first sentence in my paragraph.", "This is the second sentence in my paragraph."};
Paragraph myParagraph = new Paragraph(myStrings, 1)

Access of properties:

int paragraphLevel = myParagraph.level

Endorse on Coderwall

Comments