Swift is like C#
BASICS
Hello World
Swift
print("Hello, world!")
C#
Console.WriteLine("Hello, world!");
Variables And Constants
Swift
var myVariable = 42
myVariable = 50
let myConstant = 42
C#
var myVariable = 42;
myVariable = 50;
const int myConstant = 42;
Explicit Types
Swift
let explicitDouble: Double = 70
C#
double explicitDouble = 70d;
Type Coercion
Swift
let label = "The width is "
let width = 94
let widthLabel = label + String(width)
C#
var label = "The width is ";
var width = 94;
var widthLabel = label + width;
String Interpolation
Swift
let apples = 3
let oranges = 5
let fruitSummary = "I have \(apples + oranges) " +
                   "pieces of fruit."
C#
var apples = 3;
var oranges = 5;
var fruitSummary = $"I have {apples + oranges} " +
                   "pieces of fruit.";
Range Operator
Swift
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
    print("Person \(i + 1) is called \(names[i])")
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack
C#
var names = new[]{"Anna", "Alex", "Brian", "Jack"};
var count = names.Count();
for (var i; i< count; i++) {
    Console.WriteLine($"Person {i + 1} is called {names[i]}");
}
// Person 1 is called Anna
// Person 2 is called Alex
// Person 3 is called Brian
// Person 4 is called Jack
Inclusive Range Operator
Swift
for index in 1...5 {
    print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
C#
foreach (var index in Enumerable.Range(1,5)) {
    Console.WriteLine($"{index} times 5 is {index * 5}");
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25
BASICS
Arrays
Swift
var shoppingList = ["catfish", "water",
    "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
C#
val shoppingList = new[] { "catfish", "water",
    "tulips", "blue paint" };
shoppingList[1] = "bottle of water";
Maps
Swift
var occupations = [
    "Malcolm": "Captain",
    "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
C#
var occupations = new Dictionary {
            { "Malcolm", "Captain" },
            { "Kaylee", "Mechanic" }
        };
occupations["Jayne"] = "Public Relations";
Empty Collections
Swift
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
C#
var emptyArray = new string[0];
var emptyMap = new Dictionary<String, float>();
FUNCTIONS
Functions
Swift
func greet(_ name: String,_ day: String) -> String {
    return "Hello \(name), today is \(day)."
}
greet("Bob", "Tuesday")
C#
string greet(string name, string day) {
    return $"Hello {name}, today is {day}.";
}
greet("Bob", "Tuesday");
Tuple Return
Swift
func getGasPrices() -> (Double, Double, Double) {
    return (3.59, 3.69, 3.79)
}
C#
(double, double, double) GasPrices(long id)
{
    return (3.59, 3.69, 3.79);
}
Variable Number Of Arguments
Swift
func sumOf(_ numbers: Int...) -> Int {
    var sum = 0
    for number in numbers {
        sum += number
    }
    return sum
}
sumOf(42, 597, 12)
C#
int sumOf(params int[] args){
    var sum = 0;
    for (number in numbers) {
        sum += number;
    }
    return sum;
}
sumOf(42, 597, 12);

//can also be written
int sumOf(params int[] args)
    => args.Sum();
sumOf(42, 597, 12);
Function Type
Swift
func makeIncrementer() -> (Int -> Int) {
    func addOne(number: Int) -> Int {
        return 1 + number
    }
    return addOne
}
let increment = makeIncrementer()
increment(7)
C#
Func makeIncrementer() 
    => (int number) => { return 1 + number; };

var increment = makeIncrementer();
increment(7);

Map
Swift
let numbers = [20, 19, 7, 12]
numbers.map { 3 * $0 }
C#
var numbers = new[]{20, 19, 7, 12};
numbers.Select(i => i*3).ToArray();
Sort
Swift
var mutableArray = [1, 5, 3, 12, 2]
mutableArray.sort()
C#
new[]{1, 5, 3, 12, 2}
    .OrderBy(i => i);
Named Arguments
Swift
func area(width: Int, height: Int) -> Int {
    return width * height
}
area(width: 2, height: 3)
C#
int Area(int width, int height) { return width * height; };
Area(width: 2, height: 3);

// This is also possible with named arguments
Area(2, height: 2);
Area(height: 3, width: 2);
CLASSES
Declaration
Swift
class Shape {
    var numberOfSides = 0
    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}
C#
class Shape {
    var numberOfSides = 0;
    string SimpleDescription() 
        => $"A shape with {numberOfSides} sides.";
}
Usage
Swift
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
C#
var shape = new Shape();
shape.numberOfSides = 7;
var shapeDescription = shape.SimpleDescription();
Subclass
Swift
class NamedShape {
    var numberOfSides: Int = 0
    let name: String

    init(name: String) {
        self.name = name
    }

    func simpleDescription() -> String {
        return "A shape with \(numberOfSides) sides."
    }
}

class Square: NamedShape {
    var sideLength: Double

    init(sideLength: Double, name: String) {
        self.sideLength = sideLength
        super.init(name: name)
        self.numberOfSides = 4
    }

    func area() -> Double {
        return sideLength * sideLength
    }

    override func simpleDescription() -> String {
        return "A square with sides of length " +
	       sideLength + "."
    }
}

let test = Square(sideLength: 5.2, name: "square")
test.area()
test.simpleDescription()
C#
class NamedShape(string name) {
    var numberOfSides = 0;
    string SimpleDescription() 
        => $"A shape with {numberOfSides} sides.";
}

class Square(decimal sideLength, string name) :
        NamedShape(name) {
    
    public Square() {
        numberOfSides = 4;
    }

    int Area() 
        => sideLength*sideLength;

    override string SimpleDescription() =>
        "A square with sides of length $sideLength.";
}

val test = new Square(5.2, "square");
test.Area();
test.SimpleDescription();
Checking Type
Swift
var movieCount = 0
var songCount = 0

for item in library {
    if item is Movie {
        movieCount += 1
    } else if item is Song {
        songCount += 1
    }
}
C#
var movieCount = 0;
var songCount = 0;

foreach (var item in library) {
    if (item.GetType() == typeof(Movie)) {
        ++movieCount;
    } else if (item.GetType() == typeof(Song)) {
        ++songCount;
    }
}
Pattern Matching
Swift
let nb = 42
switch nb {
    case 0...7, 8, 9: print("single digit")
    case 10: print("double digits")
    case 11...99: print("double digits")
    case 100...999: print("triple digits")
    default: print("four or more digits")
}
C#
var nb = 42;
switch (nb)
{
    case int r when (1 <= r && r <= 9):
        Console.WriteLine("single digit");
        break;
    case 10:
        Console.WriteLine("double digits");
        break;
    case int r when (11 <= r && r <= 99):
        Console.WriteLine("double digits");
        break;
    case int r when (100 <= r && r <= 999):
        Console.WriteLine("triple digits");
        break;
    default:
        Console.WriteLine("four or more digits");
}
Downcasting
Swift
for current in someObjects {
    if let movie = current as? Movie {
        print("Movie: '\(movie.name)', " +
            "dir. \(movie.director)")
    }
}
C#
for (current in someObjects) {
    if ((current as Movie) != null) {
        Console.WriteLine($"Movie: '{(current as Movie).name}'," +
        $"dir. {(current as Movie).director}")
    }
}
Protocol
Swift
protocol Nameable {
    func name() -> String
}

func f<T: Nameable>(x: T) {
    print("Name is " + x.name())
}
C#
public interface Nameable {
    string Name();
}

void F(Nameable x) {
    Console.WriteLine("Name is " + x.Name());
}
Extensions
Swift
extension Double {
    var km: Double { return self * 1_000.0 }
    var m: Double { return self }
    var cm: Double { return self / 100.0 }
    var mm: Double { return self / 1_000.0 }
    var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm
print("One inch is \(oneInch) meters")
// prints "One inch is 0.0254 meters"
let threeFeet = 3.ft
print("Three feet is \(threeFeet) meters")
// prints "Three feet is 0.914399970739201 meters"
C#
public static double mm(this double value)
{
    return value / 1000;
}

public static double ft(this double value)
{
    return value / 3.28084;
}

var oneInch = 25.4.mm();
Console.WriteLine($"One inch is {oneInch} meters")
// prints "One inch is 0.0254 meters"
var threeFeet = 3.0.ft();
Console.WriteLine($"Three feet is {threeFeet} meters")
// prints "Three feet is 0.914399970739201 meters"