DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
  1. DZone
  2. Coding
  3. Languages
  4. Comparison of Python and Apple's Swift Programming Language Syntax

Comparison of Python and Apple's Swift Programming Language Syntax

Michael Kennedy user avatar by
Michael Kennedy
·
Dec. 03, 14 · Interview
Like (0)
Save
Tweet
Share
20.96K Views

Join the DZone community and get the full member experience.

Join For Free

As 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.

Python (language) Swift (programming language) Syntax (programming languages) Comparison (grammar)

Published at DZone with permission of Michael Kennedy, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • Using JSON Web Encryption (JWE)
  • Why Every Fintech Company Needs DevOps
  • Choosing the Best Cloud Provider for Hosting DevOps Tools
  • Top Five Tools for AI-based Test Automation

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: