You are on page 1of 1

Swift and C# Quick Reference - Language Equivalents and Code Examples

Variables Operators Control flow Classes Protocols Functions Collections Math


Swift C# Swift C# Swift C# Swift C# Swift C# Swift C# Swift C# Swift C#
boolean Bool bool arithmetic +, -, *, /, % +, -, *, /, % break, continue break, continue break, continue access init constructor protocol protocol interface anonymous closures lambdas dictionary dictionary Dictionary<S,T> minimum min System.Math.Min
constant let const assignment = = do-while do-while do-while constructor class class class method static static initialization object initializer object initializer maximum max System.Math.Max
declaration var var bitwise <<, >>, &, |, ~, ^, <<, >>, <<=, >>= &, |, ^, ~ for for for class function types delegate Protocols method func method list array List<T> power pow System.Math.Pow
float Float, Double float, double &+, &-, &*, checked for-in for-in foreach-in delegate deinit destructor~ Swift: A protocol is used to define a set of related functions that overloaded overloading overloading random numbers random System.Random.Next
overflow another type can implement.
integer Int int &/, &% unchecked if if if destructor extension extension override override override trigonometry sin System.Math.Sin
protocol PrintSelf { Lists and arrays
optional ? (optional) ? (nullable) overloading overloading overloading locking (no equivalent) lock extension subscript indexer func ToString() -> String ref parameter inout, & ref, &
} Swift: You can create lists using the array data type. Use the
tuple tuple System.Tuple range a..<b, a…b (no equivalent) queries (no equivalent) LINQ indexing : : parameter array params parameter array append function to add more elements to an existing array.
struct Box : PrintSelf { Math functions
string String (value) string (reference) relational ==, !=, >, < ==, !=, >, < switch, inheritance private, public public, private, protected, interal var top: Int = 0 return return return var boxes = [Box]() // the empty array
switch switch var left: Int = 0 boxes = [ Swift: The math functions are global functions.
fallthrough object AnyObject, Any object var height: Int = 0 Box(top: 0, left: 0, bottom: 2, right: 2),
func ToString() -> String { Box(top: 0, left: 0, bottom: 1, right: 1), // min and max support n values
Optional and nullable reference variables Operator overloading try-catch, throw assert try-catch, throw self self this return "The box is at (\(self.top), " Functions Box(top: 0, left: 0, bottom: 3, right: 4) ] var smallest = min(box0.area(), box1.area(), box2.area())
+ "\(self.left)), with height " boxes.append(Box(top: 0, left: 0, bottom: 5, right: 12)) var largest = max(box0.area(), box1.area(), box2.area())
Swift: Only optional reference variables can be set to nil. Swift: In this example, adding two boxes returns a box that using (no equivalent) using type casting is, as, as? cast, dynamic, as + "\(self.height)." Swift: Functions can be declared both as type members and in
} C#: You can create lists using array or List objects. The List object // power
contains both boxes. top-level code.
var optBox : Box? = nil unsafe (no equivalent) unsafe type alias typealias using } lets you add more elements to an existing List. func diagonal(b : Box) -> Double {
if let aBox = optBox { return sqrt(pow(Double(b.height), 2.0)
func + (r1: Box, r2: Box) -> Box { func area(box : Box) -> Double { + pow(Double(b.width), 2.0))
println(aBox.top) return (Box( while while while var boxPrint = Box(top: 0, left: 0, height: 2) return abs(Double((box.top - box.bottom)
vvar noBoxes = new Box[]{}; // the empty array
}
} top: min(r1.top, r2.top), var desc = boxPrint.ToString() Box[] boxes = {
* (box.left - box.right)))
if optBox!.top > 4 { left: min(r1.left, r2.left), yield (no equivalent) yield Classes and inheritance }
new Box(0, 0, 1, 1),
// trigonometric functions
println("Box is not at the origin.") bottom: max(r1.bottom, r2.bottom), C#: A protocol is used to define a set of related functions that new Box(0, 0, 2, 2),
} new Box(0, 0, 3, 4) }; var cos0 = cos(0.0)
right: max(r1.right, r2.right))) Swift: Classes support functions, properties, constructors, and another type can implement. C#: Methods are always declared inside a class or struct. var sin0 = sin(0.0)
} List<Box> moreBoxes = new List<Box>();
inheritance. moreBoxes.Add(new Box(0, 0, 1, 1)); var cosPi = cos(M_PI)
C#: All reference variables can be set to null. var boxSum = Box(top: 0, left: 0, bottom: 1, right: 1)
+ Box(top: 1, left: 1, bottom: 3, right: 3) For statement interface PrintSelf
{
int area(Box box) { moreBoxes.Add(new Box(0, 0, 2, 2));
class Pet { return Math.Abs((box.Top - box.Bottom) moreBoxes.Add(new Box(0, 0, 3, 4)); C#: Math functions are provided in the System namespace.
string optString = null; Swift: Swift supports C-style for loops, loops that iterate over var name : String = "" string PrintString(); * (box.Left - box.Right));
if (optString != null) { C#: Adding two boxes returns a box that contains both boxes. init(name : String) { } } // min and max support 2 values for comparison
collections, and loops that return (index, value) pairs.
Console.WriteLine(optString);
public static Box operator +(Box box1, Box box2) self.name = name
struct Box : PrintSelf Dictionary var smallest = Math.Min(box1.Area(), box2.Area());
}
{ var squares = [Box]()
for var size : Int = 1; size < 6; size++ {
}
func speak() -> String { { Overloading functions Swift: The dictionary is a built-in language type.
var largest = Math.Max(box1.Area(), box2.Area());

int? length = null; return new Box( public int Top; // pow
(int)Math.Min(box1.Top, box2.Top), squares.append( return "" Swift: Function overloading is supported wherever functions can
if (length.HasValue) { Box(top: 0, left: 0, bottom: size, right: size)) } public int Left; var emptyBoxDictionary = [Int : Box]() var diagonal = Math.Sqrt(
Console.WriteLine(length.Value); (int)Math.Min(box1.Left, box2.Left), public int Height; be declared. var boxDictionary : [Int : Box] = [ Math.Pow((box.Top - box.Bottom), 2)
(int)Math.Max(box1.Bottom, box2.Bottom), } }
} for box in squares { public string PrintString() 1 : Box(top: 0, left: 0, bottom: 2, right: 2), + Math.Pow((box.Left - box.Right), 2));
(int)Math.Max(box1.Right, box2.Right)); { func speak() -> String {
println(area(box)) class Dog : Pet { return "woof" 2 : Box(top: 0, left: 0, bottom: 1, right: 1),
} return string.Format("The box is at (%d, %d), " 3 : Box(top: 0, left: 0, bottom: 3, right: 4), // trigonometric functions
var boxSum = new Box(0, 0, 1, 1) + new Box(1, 1, 3, 3); } override func speak() -> String { }
for (index, value) in enumerate(squares) { return "woof" + "with height %d.", 4 : Box(top: 0, left: 0, bottom: 5, right: 12)] var cos0 = Math.Cos(0.0);
this.Top, this.Left, this.Height); func speak(add : String) -> String {
println("Area of box \(index) is \(area(value)).") } return speak() + ", " + add // add a new Box to the dictionary var sin0 = Math.Sin(0.0);
} } } boxDictionary[10] = var cosPi = Math.Cos(Math.PI);
} }
Box(top: 0, left: 0, bottom: 10, right: 10)
Tuples Equality and assignment C#: You can use C-style for loops and loops that iterate over var spot = Dog(name: "Spot") var box = new Box(0, 0, 1, 1); speak()
var summary = "There are \(boxDictionary.count) boxes in
collections. spot.speak() var description = box.PrintString(); speak("friend")
the dictionary." Random numbers
Swift: You create a tuple using Swift’s tuple syntax. You access the Swift: The assignment operator does not return a
C#: Methods can be overloaded inside a class or struct. Swift: Use the arc4random_uniform function to generate
tuple’s values using the value names or indexing. value, therefore you can’t use it as a conditional expression vvar squares = new List<Box>(); C#: Classes support methods, properties, constructors, events, // direct indexing into the dictionary
and you can’t do chain assignments. for (int size = 1; size < 6; size++) { and inheritance. string Speak() { var box3 = boxDictionary[3] uniformly distributed integers.
func summary(b : Box) -> (Int, Double) { squares.Add(new Box(0, 0, size, size)); return "woof"; var asum = area(box3!)
return (b.area(), b.diagonal()) var a = 6 } class Pet { } var boxStats = //generate 12 integers between 0 and 5
} var b = a foreach (var square in squares) { protected string name = ""; string Speak(string add) "The area of the box is \(area(boxDictionary[3]!))." var rns = [UInt32]()
var box = Box(top: 0, left: 0, bottom: 1, right: 1) if (b == 6) { Console.WriteLine(area(square)); public Pet() { { for i in 0...11 {
var (area, diagonal) = summary(box) a = 2 } } return Speak() + ", " + add; C#: The .NET library provides the generic Dictionary object. rns.append(arc4random_uniform(5))
var stats = (area, diagonal) } }

Enums
public Pet (string name) { }
var description = Speak(); vvar emptyBoxDictionary = new Dictionary<int, Box>();
this.name = name; var boxDictionary = new Dictionary<int, Box> {
"Area is \(area) and diagonal is \(diagonal)."
var description2 =
C#: Chain assignment is allowed and testing assignment If statement } Speak("friend");
{ 1, new Box(0, 0, 2, 2)} ,
C#: Use the Random.Next method to generate uniformly
expressions is allowed. public virtual string Speak() { distribted integers.
"Area is \(stats.0) and diagonal is \(stats.1)." { 2, new Box(0, 0, 1, 1)} ,
int b = 2;
Swift: The test condition must return a Boolean value and the
}
return ""; Reference parameters { 3, new Box(0, 0, 3, 4)} , //generate 12 integers between 0 and 5
C#: You create a tuple by instantiating a Tuple object. You access execution statements must be enclosed in braces. { 4, new Box(0, 0, 5, 12)}};
int a = b = 6; } Swift: To change a value in a function, mark the parameter as var rns = new List<int>();
the type values using Item1, Item2, etc. if ((b = 6) == 6) // add a new box to the dictionary var random = new System.Random();
var strings = ["one", "two", "three", "four"] inout and use & on the parameter in the function call. boxDictionary[10] = new Box(0, 0, 10, 10);
a = 2; if (strings[0] == "one") { class Dog : Pet { Swift C# for (int i = 0; i < 12; i++) {
Tuple<int, double> Summary(Box box) { var summary = "There are" + boxDictionary.Count rns.Add(random.Next(6));
println("First word is 'one'."); public Dog (string name) { func canAdd(a : Int, b: Int, inout sum : Int) -> Bool { + " boxes in the dictionary.";
return new Tuple<int,double>(box.Area(), this.name = name; enumerations enum enum sum = a + b }
box.Diagonal()); Range Operator }
} return true // direct indexing into the dictionary
} public override string Speak() { functions static func (no equivalent) }
var box = new Box(0, 0, 1, 1); Swift: Use the range operator to create a range of values. C#: C# allows non-Boolean test conditions and braces are not var box3 = boxDictionary[3];
return "woof"; var sum = 0 // a more robust way to select an object
var summaryTuple = Summary(box); required around the execution statements. }
for i in 1...5 { var success = canAdd(3, 4, &sum) if (boxDictionary.TryGetValue(3, out box3)) {
var description = "Area is " + summaryTuple.Item1 }
println(i) var boxStats = "The area of box 3 is "
+ " and diagonal is " + summaryTuple.Item2 + "."; string[] strings = { "one", "two", "three" };  

Generics
C#: To change a value in a function, mark the parameter as ref
} if (strings[0] == "one") {
Console.WriteLine("First word is 'one'.");
var spot = new Dog("Spot"); Enumerations and use & on the parameter in the function call. }
+ area(box3) + ".";
spot.Speak();
C#: Use the Enumerable.Range method to generate a List of } Swift: An enumeration is a type, and you can add functions to the bool CanAdd(int a, int b, ref int sum) {
integers. type definition. sum = a + b; Library Collections
foreach (int i in Enumerable.Range(1, 5).ToList()) Switch statement enum SpecialBox { }
return true;
Swift: You can use additional collection types from the Founda-
Strings and characters {
Console.WriteLine(i); Swift: Cases do not fall through unless you use the fallthrough Extension methods case Rectangle var sum = 0; tion classes. language type.
} keyword. Therefore, a break statement is not required. A default
case Square var success = CanAdd(3, 4, ref sum); Swift C#
Swift: String is a value type with properties and methods that also Swift: You can add new methods to existing classes. case GoldenRatio
// The NSSet collection is initialized with a set of
provides all the functionality of the NSString type. Strings can be case is usually required. Swift supports ranges in cases. objects. function generic functions generic functions
concatenated with string interpolation or the + operator. Overflow var aSquare = Box(top: 0, left: 0, bottom: 4, right: 4)
extension Box { static func GetSpecialType(r : Box) -> SpecialBox { Closures // You cannot add more objects after initialization.
var label = ""
func area() -> Int { return abs((self.top - self.bottom) var width = abs(r.top - r.bottom)
Swift: An anonymous function in Swift is called a closure. var strings = ["one", "two", "three"] type generic types generic types
var world = "world" * (self.left - self.right)) } var length = abs(r.left - r.right)
Swift: By default, underflow and overflow produce an error at switch SpecialBox.GetSpecialType(aSquare) { if (length == width) { var set : NSSet = NSSet(array: strings)
var helloWorld = hello + ", " + world } for str in set {
var sayHello = "\(hello), \(world)" runtime. You can use the overflow operators to suppress errors, case .Square : label = "Square" return SpecialBox.Square } var boxes = [
case .Rectangle : label = "Rectangle" else if ((Double(length)/Double(width) == 1.6) Box(top: 0, left: 0, bottom: 2, right: 2), println(str)
var capitalized = helloWorld.uppercaseString but the resulting calculation might not be what you expect. C#: You can add new methods to existing classes.
var numberOfChars = countElements(sayHello) case .GoldenRatio : label = "Golden Ratio" || (Double(width)/Double(length) == 1.6)) { Box(top: 0, left: 0, bottom: 3, right: 4) ] } Functions
var seventhChar = sayHello[advance(sayHello.startIndex, 7)] // This code does not produce an error, but the default : label = "Error" public static class BoxExtensions { return SpecialBox.GoldenRatio } var smallToLarge = sorted(boxes,
// resulting value is not the expected value. } else { { b1, b2 in return b1.area() < b2.area()}) C#: You can use additional collections from the Swift: Generic types and functions let you defer types until
var startsWithHello = sayHello.hasPrefix("hello") public static double Area(this Box box) { System.Collections namespace.
var largeInt : Int = Int.max return Math.Abs((box.Top - box.Bottom) * return SpecialBox.Rectangle} runtime.
C#: String is an alias for System.String, a class with properties, var tooLarge : Int = largeInt &+ 1 var size = "" (box.Left - box.Right)); } C#: An anonymous method in C# is called a lambda.
switch aSquare.area() { } // The HashSet collection can be initialized empty or with // selects n items at random from an array, with replacement
methods, and indexing. Strings can be concatenated with } objects.
C#: By default, underflow and overflow do not produce an error. case 0...9 : size = "small" } var isASquare = SpecialBox.GetSpecialType( Box[] boxes = { func sample<T>(list : [T], n : Int) -> [T] {
String.Format or the + operator. You can use the checked keyword so that an exception is thrown case 10...64 : size = "medium" Box(top: 0, left: 0, bottom: 2, right: 2)) new Box(0, 0, 1, 1), // You can add more objects after initialization. var result = [T]()
default : size = "large" var s = "\(isASquare == SpecialBox.Square)" new Box(0, 0, 3, 4) }; string[] strings = { "one", "two" }; for i in 1...n {
var hello = "hello"; at runtime. If you are using implicit variable declarations, the } HashSet<string> set = new HashSet<string>(strings);
var world = "world"; runtime will create variables that can contain the underflow or Type casting C#: All enumerations are instances of System.Enum class that
// sort smallest to largest
Array.Sort(boxes, (b1, b2) => b1.Area() - b2.Area()); set.Add("three");
var rand = Int(arc4random_uniform(UInt32(list.count)))
result.append(list[rand])
var helloWorld = hello + ", " + world; overflow value. C#: Switch cases fall through by default. Therefore, you need to provides several helper methods for enumerations. foreach (var str in set) { }
var sayHello = string.Format("%s, %s", hello, world); Swift: Use as for type casting and is for type checking. The Console.WriteLine(str); return result
add a break statement to each case where you don’t want fall
var
var
capitalized = helloWorld.ToUpper();
numberOfChars = sayHello.Length;
// This code throws an exception at runtime.
through. A default case is not required.
compiler will prevent you from using is if the compiler can enum SpecialBox { Functional programming } }
int largeInt = int.MaxValue; determined the type at compile time. Rectangle, var numbers = [1, 2, 3, 4, 5, 6, 7, 8]
var charN = sayHello[7]; checked { var aSquare = new Box(0, 0, 4, 4); Square, Swift: Functions are first-class objects in Swift. var asample = sample(numbers, 3)
var startsWithHello = sayHello.StartsWith("hello"); int tooLarge = largeInt + 5; var label = ""; var something : Any GoldenRatio Using Generics
} switch (GetSpecialType(aSquare)) { var rand = Int(arc4random_uniform(UInt32(10))) } func tallestBox(b1 : Box, b2 : Box) -> Box { var strings = ["one", "two", "three", "four"]
if rand > 5 { SpecialBox GetSpecialType(Box box) { return b1.height > b2.height ? b1 : b1 Swift: You can create typed-collections using generics. var ssample = sample(strings, 2)
case SpecialBox.Square :
label = "Square"; break; something = "hello" var width = Math.Abs(box.Top - box.Bottom); }
} class Sink<T> {
case SpecialBox.Rectangle : var length = Math.Abs(box.Left - box.Right); var box1 = Box(top: 0, left: 0, bottom: 2, right: 2) private var list : [T] = [] C#: Generic types and functions let you defer types until runtime.
else { var box2 = Box(top: 0, left: 0, bottom: 3, right: 4)

Programs
label = "Rectangle"; break; if (length == width) func Push(item : T) {
case SpecialBox.GoldenRatio : something = 5 return SpecialBox.Square; var compareBoxes : (Box, Box) -> Box = tallestBox // selects n items at random from an array, with
Swift and C# are C-style languages that are label = "Golden Ratio"; break; } else if (((double)length/(double)width == 1.6) var tallest = compareBoxes(box1, box2) }
list.append(item)
replacement
default : label = "Error"; break; if something is String { || ((double)width/(double)length == 1.6)) List<T> Sample<T>(T[] list, int n)
both productive and powerful. Using Swift, } return SpecialBox.GoldenRatio; C#: In C#, you create delegates that define function signatures. }
var sink = Sink<Int>() {
} else var result = new List<T>();
you can create iOS applications using Xcode. var anumber = something as Int return SpecialBox.Rectangle; Box TallestBox(Box box1, Box box2) { sink.Push(5)
sink.Push(10) Random random = new Random();
return box1.Height > box2.Height ? box1 : box2;
By leveraging your Swift skills, it’s an easy Exceptions var astring = something as String }
var boxType = GetSpecialType(new Box(0, 0, 2, 2)); }
for (int i = 0; i < n; i++)
{
Swift C# C#: C# supports type casting and uses is for type checking. var isSquare = (boxType == SpecialBox.Square); delegate Box CompareBoxes(Box box1, Box box2); C#: You can create typed-collections using generics.
int r = random.Next(list.Length);
Swift: Swift does not provide a way to catch exceptions. Instead,
transition to C#. Then using C# with Xamarin attribute (no equivalent) attributes you should program so as to avoid exceptions
var goldenName = Enum.GetName(typeof(SpecialBox), 1); public class Sink<T> result.Add(list[r]);
object something; var box1 = new Box(0, 0, 1, 1); }
{
and Visual Studio, you can create applications var length = 4
var random = new System.Random(); var box2 = new Box(0, 0, 2, 2);
private List<T> list = new List<T>(); return result;
memory automatic tree-based var rand = random.Next(10); CompareBoxes compareBoxes = TallestBox;
public void Push(T item) { }
that run on Windows, iOS, and Android. assert(length > 0, "Length cannot be 0.") if (rand > 5) { var tallestBox = compareBoxes(box1, box2);
list.Add(item);
management reference garbage something = 5; } int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8 };
Learn more at Cross-Platform Development C#: You can use try-catch for exception-handling, but catching } else { } var asample = Sample(numbers, 3);
counting collection exceptions has a significant performance impact. something = "hello"; Sink<int> sink = new Sink<int>();
in Visual Studio (http://aka.ms/T71425) and module module library try {
} sink.Push(5); string[] strings = { "one", "two", "three", "four" };
if (something is string) {

Download the code: http://aka.ms/scspostercode


sink.Push(10); var ssample = Sample(strings, 2);
Understanding the Xamarin Mobile Platform namespace (no equivalent) namespace }
var div = 1 / i; // do something
}
(http://aka.ms/Teumsa). preprocessor preprocessor catch (DivideByZeroException) {
Console.WriteLine("You can't divide by zero.");
var astring = (string)something;
(no equivalent) }
var anumber = (int)something;
directives directives

© 2014 Microsoft Corporation. All rights reserved.

You might also like