Swift C Sharp Poster
Swift C Sharp Poster
Variables
Swift
C#
boolean
Bool
bool
constant
let
const
declaration
var
var
Float, Double
float, double
Int
int
float
integer
optional
? (optional)
? (nullable)
tuple
tuple
System.Tuple
string
String (value)
string (reference)
Operators
Swift
C#
arithmetic
+, -, *, /, %
+, -, *, /, %
assignment
checked
&/, &%
unchecked
bitwise
overflow
var
var
var
var
var
var
var
world = "world"
helloWorld = hello + ", " + world
sayHello = "\(hello), \(world)"
capitalized = helloWorld.uppercaseString
numberOfChars = countElements(sayHello)
seventhChar = sayHello[advance(sayHello.startIndex, 7)]
startsWithHello = sayHello.hasPrefix("hello")
hello = "hello";
world = "world";
helloWorld = hello + ", " + world;
sayHello = string.Format("%s, %s", hello, world);
capitalized = helloWorld.ToUpper();
numberOfChars = sayHello.Length;
charN = sayHello[7];
startsWithHello = sayHello.StartsWith("hello");
if
do-while
do-while
for
for
for-in
foreach-in
if
if
access
constructor
class
delegate
destructor
init
constructor
class
class
function types
delegate
deinit
destructor~
extension
extension
lock
extension
subscript
indexer
range
a..<b, ab
(no equivalent)
queries
(no equivalent)
LINQ
indexing
relational
private, public
AnyObject, Any
object
self
this
cast, dynamic, as
typealias
using
Operator overloading
switch
try-catch, throw
switch,
switch
fallthrough
assert
try-catch, throw
inheritance
object
self
using
(no equivalent)
using
type casting
unsafe
(no equivalent)
unsafe
type alias
while
while
while
yield
(no equivalent)
yield
C#: Adding two boxes returns a box that contains both boxes.
public static Box operator +(Box box1, Box box2)
{
return new Box(
(int)Math.Min(box1.Top, box2.Top),
(int)Math.Min(box1.Left, box2.Left),
(int)Math.Max(box1.Bottom, box2.Bottom),
(int)Math.Max(box1.Right, box2.Right));
}
var boxSum = new Box(0, 0, 1, 1) + new Box(1, 1, 3, 3);
var a
var b
if (b
a
}
= 6
= a
== 6) {
= 2
Range Operator
Swift: Use the range operator to create a range of values.
for i in 1...5 {
println(i)
}
Programs
Swift
C#
attribute
(no equivalent)
attributes
memory
automatic
tree-based
reference
garbage
counting
module
collection
library
(no equivalent)
namespace
namespace
preprocessor
directives
(no equivalent)
preprocessor
directives
C#: You can use C-style for loops and loops that iterate over
collections.
If statement
Swift: The test condition must return a Boolean value and the
execution statements must be enclosed in braces.
Swift: Cases do not fall through unless you use the fallthrough
keyword. Therefore, a break statement is not required. A default
case is usually required. Swift supports ranges in cases.
Overflow
module
Swift: Swift supports C-style for loops, loops that iterate over
collections, and loops that return (index, value) pairs.
Switch statement
management
For statement
Swift: String is a value type with properties and methods that also
provides all the functionality of the NSString type. Strings can be
concatenated with string interpolation or the + operator.
for-in
break, continue
C#
(no equivalent)
for
break, continue
Swift
locking
Swift: You create a tuple using Swifts tuple syntax. You access the
tuples values using the value names or indexing.
do-while
C#
Protocols
overloading
break, continue
Swift
Classes
overloading
overloading
Tuples
Control flow
Exceptions
Swift: Swift does not provide a way to catch exceptions. Instead,
you should program so as to avoid exceptions
var length = 4
assert(length > 0, "Length cannot be 0.")
C#: You can use try-catch for exception-handling, but catching
exceptions has a significant performance impact.
try {
var div = 1 / i;
}
catch (DivideByZeroException) {
Console.WriteLine("You can't divide by zero.");
}
Swift
C#
closures
lambdas
class method
static
static
Protocols
method
func
method
overloaded
overloading
overloading
override
override
override
protocol PrintSelf {
func ToString() -> String
}
ref parameter
inout, &
ref, &
parameter array
params
parameter array
return
return
return
protocol
Extension methods
Swift: You can add new methods to existing classes.
extension Box {
func area() -> Int { return abs((self.top - self.bottom)
* (self.left - self.right)) }
}
C#: You can add new methods to existing classes.
public static class BoxExtensions {
public static double Area(this Box box) {
return Math.Abs((box.Top - box.Bottom) *
(box.Left - box.Right));
}
}
Type casting
Swift: Use as for type casting and is for type checking. The
compiler will prevent you from using is if the compiler can
determined the type at compile time.
var something : Any
var rand = Int(arc4random_uniform(UInt32(10)))
if rand > 5 {
something = "hello"
}
else {
something = 5
}
if something is String {
}
var anumber = something as Int
var astring = something as String
C#: C# supports type casting and uses is for type checking.
object something;
var random = new System.Random();
var rand = random.Next(10);
if (rand > 5) {
something = 5;
} else {
something = "hello";
}
if (something is string) {
// do something
}
var astring = (string)something;
var anumber = (int)something;
Swift
C#
protocol
interface
anonymous
functions
Reference parameters
enum
static func
(no equivalent)
Enumerations
Swift: An enumeration is a type, and you can add functions to the
type definition.
enum SpecialBox {
case Rectangle
case Square
case GoldenRatio
static func GetSpecialType(r : Box) -> SpecialBox {
var width = abs(r.top - r.bottom)
var length = abs(r.left - r.right)
if (length == width) {
return SpecialBox.Square }
else if ((Double(length)/Double(width) == 1.6)
|| (Double(width)/Double(length) == 1.6)) {
return SpecialBox.GoldenRatio }
else {
return SpecialBox.Rectangle}
}
}
var isASquare = SpecialBox.GetSpecialType(
Box(top: 0, left: 0, bottom: 2, right: 2))
var s = "\(isASquare == SpecialBox.Square)"
C#: All enumerations are instances of System.Enum class that
provides several helper methods for enumerations.
enum SpecialBox {
Rectangle,
Square,
GoldenRatio
}
SpecialBox GetSpecialType(Box box) {
var width = Math.Abs(box.Top - box.Bottom);
var length = Math.Abs(box.Left - box.Right);
if (length == width)
return SpecialBox.Square;
else if (((double)length/(double)width == 1.6)
|| ((double)width/(double)length == 1.6))
return SpecialBox.GoldenRatio;
else
return SpecialBox.Rectangle;
}
var boxType = GetSpecialType(new Box(0, 0, 2, 2));
var isSquare = (boxType == SpecialBox.Square);
var goldenName = Enum.GetName(typeof(SpecialBox), 1);
initialization
object initializer
object initializer
array
List<T>
list
Closures
Functional programming
Swift: Functions are first-class objects in Swift.
func tallestBox(b1 : Box, b2 : Box) -> Box {
return b1.height > b2.height ? b1 : b1
}
var box1 = Box(top: 0, left: 0, bottom: 2, right: 2)
var box2 = Box(top: 0, left: 0, bottom: 3, right: 4)
var compareBoxes : (Box, Box) -> Box = tallestBox
var tallest = compareBoxes(box1, box2)
C#: In C#, you create delegates that define function signatures.
Box TallestBox(Box box1, Box box2) {
return box1.Height > box2.Height ? box1 : box2;
}
delegate Box CompareBoxes(Box box1, Box box2);
var box1 = new Box(0, 0, 1, 1);
var box2 = new Box(0, 0, 2, 2);
CompareBoxes compareBoxes = TallestBox;
var tallestBox = compareBoxes(box1, box2);
Math
Swift
C#
minimum
min
System.Math.Min
maximum
max
System.Math.Max
power
pow
System.Math.Pow
random
System.Random.Next
sin
System.Math.Sin
random numbers
trigonometry
Overloading functions
enum
Dictionary<S,T>
enumerations
dictionary
dictionary
C#: You can create lists using array or List objects. The List object
lets you add more elements to an existing List.
C#
C#
Swift
Swift
Functions
interface PrintSelf
{
string PrintString();
}
Enums
Collections
class Pet {
protected string name = "";
public Pet() {
}
public Pet (string name) {
this.name = name;
}
public virtual string Speak() {
return "";
}
}
class Dog : Pet {
public Dog (string name) {
this.name = name;
}
public override string Speak() {
return "woof";
}
}
Functions
Dictionary
Swift: The dictionary is a built-in language type.
var emptyBoxDictionary = [Int : Box]()
var boxDictionary : [Int : Box] = [
1 : Box(top: 0, left: 0, bottom: 2, right: 2),
2 : Box(top: 0, left: 0, bottom: 1, right: 1),
3 : Box(top: 0, left: 0, bottom: 3, right: 4),
4 : Box(top: 0, left: 0, bottom: 5, right: 12)]
// add a new Box to the dictionary
boxDictionary[10] =
Box(top: 0, left: 0, bottom: 10, right: 10)
var summary = "There are \(boxDictionary.count) boxes in
the dictionary."
// direct indexing into the dictionary
var box3 = boxDictionary[3]
var asum = area(box3!)
var boxStats =
"The area of the box is \(area(boxDictionary[3]!))."
C#: The .NET library provides the generic Dictionary object.
vvar emptyBoxDictionary = new Dictionary<int, Box>();
var boxDictionary = new Dictionary<int, Box> {
{ 1, new Box(0, 0, 2, 2)} ,
{ 2, new Box(0, 0, 1, 1)} ,
{ 3, new Box(0, 0, 3, 4)} ,
{ 4, new Box(0, 0, 5, 12)}};
// add a new box to the dictionary
boxDictionary[10] = new Box(0, 0, 10, 10);
var summary = "There are" + boxDictionary.Count
+ " boxes in the dictionary.";
Math functions
Swift: The math functions are global functions.
// min and max support n values
var smallest = min(box0.area(), box1.area(), box2.area())
var largest = max(box0.area(), box1.area(), box2.area())
// power
func diagonal(b : Box) -> Double {
return sqrt(pow(Double(b.height), 2.0)
+ pow(Double(b.width), 2.0))
}
// trigonometric functions
var cos0 = cos(0.0)
var sin0 = sin(0.0)
var cosPi = cos(M_PI)
C#: Math functions are provided in the System namespace.
// min and max support 2 values for comparison
var smallest = Math.Min(box1.Area(), box2.Area());
var largest = Math.Max(box1.Area(), box2.Area());
// pow
var diagonal = Math.Sqrt(
Math.Pow((box.Top - box.Bottom), 2)
+ Math.Pow((box.Left - box.Right), 2));
// trigonometric functions
var cos0 = Math.Cos(0.0);
var sin0 = Math.Sin(0.0);
var cosPi = Math.Cos(Math.PI);
Random numbers
Swift: Use the arc4random_uniform function to generate
uniformly distributed integers.
//generate 12 integers between 0 and 5
var rns = [UInt32]()
for i in 0...11 {
rns.append(arc4random_uniform(5))
}
C#: Use the Random.Next method to generate uniformly
distribted integers.
//generate 12 integers between 0 and 5
var rns = new List<int>();
var random = new System.Random();
for (int i = 0; i < 12; i++) {
rns.Add(random.Next(6));
}
Generics
Library Collections
Swift: You can use additional collection types from the Foundation classes. language type.
// The NSSet collection is initialized with a set of
objects.
// You cannot add more objects after initialization.
var strings = ["one", "two", "three"]
var set : NSSet = NSSet(array: strings)
for str in set {
println(str)
}
function
type
Swift
C#
generic functions
generic functions
generic types
generic types
Functions
Swift: Generic types and functions let you defer types until
runtime.
Using Generics
Swift: You can create typed-collections using generics.
class Sink<T> {
private var list : [T] = []
func Push(item : T) {
list.append(item)
}
}
var sink = Sink<Int>()
sink.Push(5)
sink.Push(10)
C#: Generic types and functions let you defer types until runtime.