This is a guest post from Bradley Needham, one of my DevelopMentor colleagues. He manages our C++ curriculum and was inspired by my Swift / Python comparison (Comparison of Python and Apple’s Swift Programming Language Syntax).
Here’s Bradley and C++ vs. Swift. Thanks Bradley!
Image may be NSFW.
Clik here to view.
When Michael wrote his Python vs Swift article, I found it interesting how similar each of these languages (Python, C#, and Swift) are and thought it might be worth having a similar article comparing Modern C++ and Swift.
Code Comments
Swift has the same comments as C++ with a twist:
// C++ single line comment // Swift single line comment /* C++ Multiline comment but cannot nest */ /* Swift Multiline comment but /*can*/ nest */
Constants and Variables
Swift is strictly typed but also makes use of type inference. C++ is also strictly typed and makes use of type inference.
var age = 25 // An inferred initialized Int variable in Swift var salary : Float // An explicit uninitialized Float in Swift auto age = 25; // An inferred initialized int variable in C++ double salary; // An explicit uninitialized float in C++ let pi = 3.1415 // Constant in Swift const auto pi = 3.1415; // Constant in C++
Strings
Swift treats double-quoted literals as the String type. C++ treats double-quoted literals as a zero-terminated const char[]
but does have a standard string type that can be used.
var msg = "A String in Swift" var s = msg.utf16Count // s is 17 auto msg = "A zero-terminated const char[] in C++"; auto s = msg.length(); // error no such member auto msg1 = std::string("A string in C++"); auto s = msg.length(); // s is 15
Both Swift and C++ support unicode. Swift provides the String type and C++ std::u16string
.
Arrays
Swift supports dynamically-growable arrays. C++ has std::vector
which offers similar functionality.
Declaring
// Swift var nums = [1,2,3,5,7,11] var strings = ["hello", "how are you", "goodbye"] // C++ auto nums = std::vector {1,2,3,5,7,11}; auto strings = std::vector {"hello", "how are you", "goodbye"};
Using
Here is a comparison of using arrays in the two languages.
// Iteration in Swift var nums = [1,2,3,5,7,11] for n in nums { println(n) } // Iteration in C++ auto nums = std::vector {1,2,3,5,7,11}; for (auto n : nums) { std::cout << n << "n"; } // Updating values nums[2] = 10 // Swift nums[2] = 10 // C++ // Check for elements // Swift if !nums.isEmpty { println("nums is not empty") } // C++ if (!nums.empty()) { std::cout << "nums is not emptyn"; } // Adding items nums.append(7) // Swift nums.push_back(7) // C++
Dictionaries
Swift has build in support for dictionaries. C++ has std::map
and std::unordered_map
.
// Swift var cust = ["name": "Brad", "state": "CA"] // initialize var the_name = cust["name"] // access value cust["name"] = "Bradley" // change value cust["hobby"] = "Swimming" // add key/value cust.removeValueForKey("hobby") // remove key/value // C++ auto cust = std::map<std::string, std::string> {{"name", "Brad"}, {"state", "CA"}}; auto the_name = cust["name"]; // access value cust["name"] = "Bradley"; // change value cust["hobby"] = "Swimming"; // add key/value cust.erase(cust.find("hobby")); // remove key/value
Both languages also allow for checking for the existence of a key
// Swift if let theHobby = cust["hobby"] { println("Your hobby is (theHobby)") } // C++ try { auto theHobby = cust.at("hobby"); std::cout << "Your hobby is " << theHobby << “\n"; } catch (...) { } // C++ auto it = cust.find("hobby"); if (it != cust.end()) { std::cout << "Your hobby is " << it->second << “\n"; }
Conditional statements
Swift allows the removal of parenthesis, C++ requires them.
// Swift var n = 42 if n < 40 { println("n is less than 40") } else { println("n is 40 or above") } if (n == 42) { // works with or without parenthesis println("the answer") } // C++ if (n < 40) { // must have parenthesis println("n is less than 40") } else { println("n is 40 or above") } if (n == 42) { println("the answer") } // conditional and logic operators are the same // &&, ||, <=, >=, !, ==, etc.
Switch statements
Default behavior differs between languages. At the end of a case statement, Swift has an automatic break while C++ falls through to next case.
// Swift switch (i) { case 1: // do work case 2: // do work default: // do work } // C++ switch (i) { case 1: // do work break; // must explicity break out of switch case 2: // do work break; // must explicity break out of switch default: // do work break; // must explicity break out of switch }
fallthrough
keyword is used to fall through a case in Swift. In C++, removal of the break causes a fall through
// Swift switch i { case 1: // do work case 2: // do work fallthrough // must explicity fall through default: // do work } // C++ switch (i) { case 1: // do work break; // must explicitly break out of switch case 2: // do work // no break will fall through default: // do work break; // must explicitly break out of switch }
Swift allows for switching on Strings, C++ does not
// Swift only switch str { case "hello": // do work case "goodbye": // do work default: // do work }
Swift allows for range cases. C++ uses the default fall through to accomplish similar functionality
// Swift switch i { case 1...3: // do work default: // do work } // C++ switch (i) { case 1: case 2: case 3: // do work break; default: //do work break; }
Functions
Both languages have rich support for functions, including lambdas, function objects, and tuples.
// Swift func getUser(id : Int) -> (String, String) { var username = "username" var email = "email" return (username, email) } var (n, e) = getUser(1) // n = username, e = email // C++11 auto getUser(int id) -> std::tuple<std::string, std::string> { auto username = "username"; auto email = "email"; return std::make_tuple(username, email); } // C++14 auto getUser(int id) { auto username = "username"; auto email = "email"; return std::make_tuple(username, email); } std::string n, e; std::tie(n, e) = getUser(1);
Conclusion
Most modern 3rd-generation languages have many similarities, it just takes getting use to the small differences in order to be able to code between them. Once you get past the language issues, you can spend your time on the platform API which is the thing that really lets you get your work done.
Image may be NSFW.Clik here to view.
