Dart vs Swift: a comparison

This is not required if there is no return value (Void):func foo()func bar() -> IntRead more:Dart FunctionsSwift FunctionsNamed and un-named parametersBoth languages support named and un-named parameters.In Swift, parameters are named by default:func foo(name: String, age: Int, height: Double)foo(name: "Andrea", age: 34, height: 1.84)In Dart, we define named parameters with curly braces ({}):void foo({String name, int age, double height});foo(name: 'Andrea', age: 34, height: 1.84);In Swift, we define un-named parameters by using an underscore (_) as an external parameter:func foo(_ name: String, _ age: Int, _ height: Double)foo("Andrea", 34, 1.84)In Dart, we define un-named parameters by omitting the curly braces ({}):void foo(String name, int age, double height);foo('Andrea', 34, 1.84);Read more: Function Argument Labels and Parameter Names in Swift.Optional and default parametersBoth languages support default parameters.In Swift, you can define a default value for any parameter in a function by assigning a value to the parameter after that parameter’s type..If a default value is defined, you can omit that parameter when calling the function.func foo(name: String, age: Int = 0, height: Double = 0.0) foo(name: "Andrea", age: 34) // name: "Andrea", age: 34, height: 0.0Read more: Default Parameter Values in Swift.In Dart, optional parameters can be either positional or named, but not both.// positional optional parametersvoid foo(String name, [int age = 0, double height = 0.0]);foo('Andrea', 34); // name: 'Andrea', age: 34, height: 0.0// named optional parametersvoid foo({String name, int age = 0, double height = 0.0});foo(name: 'Andrea', age: 34); // name: 'Andrea', age: 34, height: 0.0Read more: Optional parameters in Dart.ClosuresBeing first-class objects, functions can be passed as arguments to other functions, or assigned to variables.In this context, functions are also known as closures.Here is a Dart example of a function that iterates over a list of items, using a closure to print the index and contents of each item:final list = ['apples', 'bananas', 'oranges'];list.forEach((item) => print('${list.indexOf(item)}: $item'));The closure takes one argument (item), prints the index and value of that item, and returns no value.Note the use of the arrow notation (=>)..This can used in place of a single return statement inside curly braces:list.forEach((item) { print('${list.indexOf(item)}: $item'); });The same code in Swift looks like this:let list = ["apples", "bananas", "oranges"]list.forEach({print("(String(describing: list.firstIndex(of: $0))) ($0)")})In this case, we don’t specify a name for the argument passed to the closure, and use $0 instead to mean the first argument..This is entirely optional and we can use a named parameter if we prefer:list.forEach({ item in print("(String(describing: list.firstIndex(of: item))) (item)")})Closures are often used as completion blocks for asynchronous code in Swift (see section below about asynchronous programming).Read more:Dart Anonymous functionsSwift ClosuresTuplesFrom the Swift Docs:Tuples group multiple values into a single compound value..The values within a tuple can be of any type and don’t have to be of the same type as each other.These can be used as small light-weight types, and are useful when defining functions with multiple return values.Here is how to use tuples in Swift:let t = ("Andrea", 34, 1.84)print(t.0) // prints "Andrea"print(t.1) // prints 34print(t.2) // prints 1.84Tuples are supported with a separate package in Dart:const t = const Tuple3<String, int, double>('Andrea', 34, 1.84);print(t.item1); // prints 'Andrea'print(t.item2); // prints 34print(t.item3); // prints 1.84Control flowBoth languages provide a variety of control flow statements.Examples of this are if conditionals, for and while loops, switch statements.Covering these here would be quite lengthy, so I refer to the official docs:Swift Control FlowDart Control Flow StatementsCollections (arrays, sets, maps)Arrays / ListsArrays are ordered groups of objects.Arrays can be created as Lists in Dart:var emptyList = <int>[]; // empty listvar list = [1, 2, 3]; // list literallist.length; // 3list[1]; // 2Arrays have a built-in type in Swift:var emptyArray = [Int]() // empty arrayvar array = [1, 2, 3] // array literalarray.count // 3array[1] // 2SetsQuoting the Swift docs:A set stores distinct values of the same type in a collection with no defined ordering..You can use a set instead of an array when the order of items is not important, or when you need to ensure that an item only appears once.This is defined with the Set class in Dart.var emptyFruits = Set<String>();var fruits = Set<String>.from(['apple', 'banana']); // set from IterableLikewise, in Swift:var emptyFruits = Set<String>()var fruits = Set<String>(["apple", "banana"])Maps / DictionariesThe Swift docs have a good definition for a map/dictionary:A dictionary stores associations between keys of the same type and values of the same type in a collection with no defined ordering..Each value is associated with a unique key, which acts as an identifier for that value within the dictionary.Maps are defined like so in Dart:var namesOfIntegers = Map<Int,String>(); // empty mapvar airports = { 'YYZ': 'Toronto Pearson', 'DUB': 'Dublin' }; // map literalMaps are called dictionaries in Swift:var namesOfIntegers = [Int: String]() // empty dictionaryvar airports = ["YYZ": "Toronto Pearson", "DUB": "Dublin"] // dictionary literalRead More:Dart CollectionsSwift Collections (in particular I recommend the section about Sets).Nullability & OptionalsIn Dart, any object can be null..And trying to access methods or variables of null objects results in a null pointer exception..This is one the most common source of errors (if not the most common) in computer programs.Since the beginning, Swift had optionals, a built-in language feature for declaring if objects can or cannot have a value..Quoting the docs:You use optionals in situations where a value may be absent..An optional represents two possibilities: Either there is a value, and you can unwrap the optional to access that value, or there isn’t a value at all.In contrast to this, we can use non-optional variables to guarantee that they will always have a value:var x: Int?.// optionalvar y: Int = 1 // non-optional, must be initializedNote: saying that a Swift variable is optional is roughly the same as saying that a Dart variable can be null.Without language-level support for optionals, we can only check at runtime if a variable is null.With optionals, we encode this information at compile-time instead.. More details

Leave a Reply