Escolar Documentos
Profissional Documentos
Cultura Documentos
Enums
var stats = (area, diagonal) public Pet (string name) { }
var description = Speak(); vvar emptyBoxDictionary = new Dictionary<int, Box>();
this.name = name;
"Area is \(area) and diagonal is \(diagonal)." C#: Chain assignment is allowed and testing assignment If statement } Speak("friend"); var boxDictionary = new Dictionary<int, Box> {
{ 1, new Box(0, 0, 2, 2)} ,
C#: Use the Random.Next method to generate uniformly
var description2 = expressions is allowed. public virtual string Speak() { distribted integers.
{ 2, new Box(0, 0, 1, 1)} ,
"Area is \(stats.0) and diagonal is \(stats.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);
Tuple<int, double> Summary(Box box) {
a = 2; if (strings[0] == "one") { class Dog : Pet { Swift C# var summary = "There are" + boxDictionary.Count
for (int i = 0; i < 12; i++) {
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 }
box.Diagonal()); Range Operator }
}
sum = a + b
return true // direct indexing into the dictionary
}
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 public override string Speak() { functions static func (no equivalent) } var box3 = boxDictionary[3];
return "woof"; var sum = 0
var summaryTuple = Summary(box); required around the execution statements. }
// a more robust way to select an object
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) string[] strings = { "one", "two", "three" }; var boxStats = "The area of box 3 is "
Generics
+ " and diagonal is " + summaryTuple.Item2 + "."; 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 {
Swift: Cases do not fall through unless you use the fallthrough Extension methods case Rectangle var sum = 0; tion classes. language type.
Console.WriteLine(i);
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. function generic functions generic functions
Closures
static func GetSpecialType(r : Box) -> SpecialBox { objects.
concatenated with string interpolation or the + operator. Overflow var aSquare = Box(top: 0, left: 0, bottom: 4, right: 4)
extension Box {
func area() -> Int { return abs((self.top - self.bottom) var width = abs(r.top - r.bottom) // You cannot add more objects after initialization.
type generic types generic types
var label = "" * (self.left - self.right)) } var length = abs(r.left - r.right) Swift: An anonymous function in Swift is called a closure. var strings = ["one", "two", "three"]
var world = "world" Swift: By default, underflow and overflow produce an error at var set : NSSet = NSSet(array: strings)
var helloWorld = hello + ", " + world switch SpecialBox.GetSpecialType(aSquare) { } if (length == width) {
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 = [
println(str)
but the resulting calculation might not be what you expect. case .Rectangle : label = "Rectangle" else if ((Double(length)/Double(width) == 1.6) Box(top: 0, left: 0, bottom: 2, right: 2),
C#: You can add new methods to existing classes.
var
var
capitalized = helloWorld.uppercaseString
numberOfChars = countElements(sayHello) case .GoldenRatio : label = "Golden Ratio" || (Double(width)/Double(length) == 1.6)) { Box(top: 0, left: 0, bottom: 3, right: 4) ] } Functions
// This code does not produce an error, but the default : label = "Error" return SpecialBox.GoldenRatio } var smallToLarge = sorted(boxes,
var seventhChar = sayHello[advance(sayHello.startIndex, 7)]
// resulting value is not the expected value. }
public static class BoxExtensions {
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 C#: By default, underflow and overflow do not produce an error. case 0...9 : size = "small"
}
var isASquare = SpecialBox.GetSpecialType( Box[] boxes = { objects. func sample<T>(list : [T], n : Int) -> [T] {
String.Format or the + operator. } // You can add more objects after initialization.
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), 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 {
at runtime. If you are using implicit variable declarations, the
Type casting
var hello = "hello"; } // sort smallest to largest HashSet<string> set = new HashSet<string>(strings); var rand = Int(arc4random_uniform(UInt32(list.count)))
var world = "world"; runtime will create variables that can contain the underflow or C#: All enumerations are instances of System.Enum class that Array.Sort(boxes, (b1, b2) => b1.Area() - b2.Area()); set.Add("three"); 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);
add a break statement to each case where you don’t want fall return result
var capitalized = helloWorld.ToUpper(); // 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 } }
var numberOfChars = sayHello.Length; 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 { Square, Swift: Functions are first-class objects in Swift. var asample = sample(numbers, 3)
var startsWithHello = sayHello.StartsWith("hello"); int tooLarge = largeInt + 5;
var aSquare = new Box(0, 0, 4, 4);
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 {
Programs
label = "Rectangle"; break; if (length == width) var box2 = Box(top: 0, left: 0, bottom: 3, right: 4) func Push(item : T) {
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 case SpecialBox.GoldenRatio :
label = "Golden Ratio"; break; } else if (((double)length/(double)width == 1.6) var tallest = compareBoxes(box1, box2) }
list.append(item)
replacement
if something is String { || ((double)width/(double)length == 1.6)) List<T> Sample<T>(T[] list, int n)
both productive and powerful. Using Swift, }
default : label = "Error"; break;
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();
By leveraging your Swift skills, it’s an easy Exceptions var astring = something as String }
}
return box1.Height > box2.Height ? box1 : box2; for (int i = 0; i < n; i++)
{
Swift C# var boxType = GetSpecialType(new Box(0, 0, 2, 2)); C#: You can create typed-collections using generics.
Swift: Swift does not provide a way to catch exceptions. Instead, C#: C# supports type casting and uses is for type checking. var isSquare = (boxType == SpecialBox.Square); delegate Box CompareBoxes(Box box1, Box box2); int r = random.Next(list.Length);
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 random = new System.Random(); var box2 = new Box(0, 0, 2, 2); {
return result;
memory automatic tree-based var length = 4 var rand = random.Next(10); CompareBoxes compareBoxes = TallestBox; private List<T> list = new List<T>();
}
that run on Windows, iOS, and Android. assert(length > 0, "Length cannot be 0.") if (rand > 5) { var tallestBox = compareBoxes(box1, box2); public void Push(T item) {