Comparison of Python and Apple's Swift Programming Language Syntax
Join the DZone community and get the full member experience.
Join For FreeAs a Python and C# developer, I have been intrigued ever since Apple announced the Swift programming language to cheering crowds at WWDC 2014.
This post will explore the syntax of Python 3 vs Swift. I was inspired by Chris Pietschmann’s post Basic Comparison of C# and Apple Swift Programming Language Syntax for C# and Swift. So here is the Python version.
Before you review the syntax comparisons, you may want to download the code in Python, Swift or both:
Downloads
- Python: PythonVsSwift.py.zip
- Swift: SwiftComparedToPython.playground.zip
Code Comments
Both languages have comments:
# Python has single line comments // Swift has single line comments /* Swift also has multi-line comments in C style */
Declaring Constants and Variables
Swift has rich support for type inference and constants. Python is dynamic and does not natively support constants.
name = "A string variable in Python" age = 42 # An integer variable in Python var name = "A string variable in Swift" var age : Int // An explicit integer variable in Swift age = 42 let pi = 3.14 // Constant in Swift
Integer Bounds
# Python does not have upper bounds for integer numbers (Python 3) large_nun = 10000000000000000000000000000000000000000000000000000 // Swift var a = Int32.min var b = Int32.max
Type Inference
Swift is a strongly-typed language which makes heavy use of type-inference although you can declare explicit types. Python is a dynamic language so while there is a type system it is not evident in the syntax.
# Python name = "Michael" # string variable, but can change name = 42 # would run n = 42 # currently an int d = 42.0 # currently a float // Swift var name = "Michael" // string name = 42 // Error var n = 42 // int var d = 42.0 // double
String Comparison
Python and Swift both have Unicode strings. Python generally has richer string support than Swift (especially around string formatting).
# python a = "some text" b = "some text" if a == b: print("The strings are equal") # swift var a = "some text" var b = "some text" if a == b { println("The strings are equal") }
Both languages have many functions on strings
# python if a.startswith("some"): print("Starts with some") if a.endswith("some"): print("Ends with some") // swift if a.hasPrefix("some") { println("Starts with some") } if a.hasSuffix("some") { println("Endss with some") }
String Upper or Lower Case
# python s = "some text" u = s.upper() l = s.lower() // swift var s = "some text" var u = s.uppercaseString var l = s.lowercaseString
Declaring Arrays
Neither language has strict array types in the sense of C-based arrays. The arrays in Swift and Python are closer to lists. Python’s lists are not typed (hence can be heterogeneous).
# python nums = [1,1,3,5,8,13,21] // swift var nums = [1,1,3,5,8,13,21] // int array var strings = ["one", "two", "three"] // string array
Working with Arrays
# Iteration in python nums = [1,1,3,5,8,13,21] for n in nums: print(n) # Iteration in Swift: var nums = [1,1,3,5,8,13,21] for n in nums { println(n) } # Element access n = nums[2] # python, n = 3 var n = nums[2] # swift, n = 3 # Updating values nums[2] = 10 # python nums[2] = 10 # swift # Check for elements # python if nums: print("Nums is not empty") // swift if !nums.isEmpty { println("Nums is not empty") } # Adding items: nums.append(7) # python nums.append(7) # swift # Slicing nums = [1,1,3,5,8,13,21] middle = nums[2:4] # python, middle = [3, 5] var middle = nums[2..<4] // swift, middle = [3,5]
Dictionaries
Dictionaries play important roles in both languages and are fundamental types.
# python d = dict(name="Michael", state="OR") d = { "name": "Michael", "state": "OR" } the_name = d["name"] // swift var empty_dict = Dictionary<String, String>() var d = ["name": "Michael", "state": "OR"] var the_name = d["name"]
Adding items is the same in both languages. Removing entries is arguably clearer in Swift.
# add an item d["hobby"] = "Biking" # python d["hobby"] = "Biking" // swift # remove an item del d["hobby"] # python d.removeValueForKey("hobby") // swift
Checking for the existence of a key can also be done in both languages.
# python if "hobby" in d: print("Your hobby is " + d["hobby"]) // swift if let theHobby = d["hobby"] { println("Your hobby is \(theHobby)") }
Conditional Statements
Conditional statements are quite similar.
# python n = 40 m = 2 if n > 40: print("n bigger than 40") elif m == 2 and n % 2 == 0: print("m is 2") else: print("else") # swift var n = 40 var m = 2 if n > 40 { println("n bigger than 40") } else if m == 2 && n % 2 == 0 { print("m is 2") } else { print("else") }
Switch statements
Swift has them, Python does not.
Functions
Functions are very rich in both languages. They have closures, multiple return values, lambdas, and more. Here is a simple version. Note that this example also leverages tuples and tuple unpacking in both languages.
# python def get_user(id): name = "username" email = "email" return name,email n, e = get_user(1) // 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
Conclusion
As you can see, the similarities to Python are striking. I expect with some experience transitioning between the languages will be easy. The major differences actually lie underneath at the standard library vs cocoa base classes. As with most languages, this is where the real mastery of the platform happens.
Published at DZone with permission of Michael Kennedy, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments