惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
雷峰网
雷峰网
The Register - Security
The Register - Security
The Cloudflare Blog
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
I
InfoQ
博客园 - 三生石上(FineUI控件)
H
Help Net Security
博客园 - 司徒正美
Vercel News
Vercel News
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
B
Blog
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
L
LangChain Blog
人人都是产品经理
人人都是产品经理
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recorded Future
Recorded Future
小众软件
小众软件
Martin Fowler
Martin Fowler
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Apple Machine Learning Research
Apple Machine Learning Research
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
Y
Y Combinator Blog
V
Visual Studio Blog
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
V
V2EX
Blog — PlanetScale
Blog — PlanetScale

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
Make Your Swift Code Expressive: Addition Operator Use Cases
Dmitri Pavlutin · 2016-11-16 · via Dmitri Pavlutin Blog

I like reading short and expressive code. Because developer spends more time reading code than writing, expressiveness often is obligatory.

Unless shortness does not obscure the intent, I favor concise expressions over longer ones. For example:


import Foundation

let greeting = "Hello, "

let who = "World"

let message1 = greeting + who

let message2 = greeting.appending(who)

print(message1) // => "Hello, World"

print(message2) // => "Hello, World"


The sample shows 2 options to concatenate strings: using addition operator + or appending(_) string method.
What option do you like more? I guess the concise one greeting + who.

The operator overloading in Swift enables to write short expressions. Many types like Int, String, Array overload addition (+) and addition assignment (+=) operators. It makes the manipulation of the corresponding types more intuitive.

Would you like to write expressive code? I'm sure you do! So let's continue with an interesting list of types that support operator overloading for + and +=.
The alternative methods with the same behavior are also presented, for comparison purposes.

1. Sum numbers

Obviously the regular usage of addition operator is meant to perform arithmetic addition on numbers. For instance, 4 + 8 is evaluated to 12.

Because Swift is type-safe, you can apply + and += operators when both operands are exactly the same type (Int + Int, but not UInt + Int or Float + Int).

All Swift number types Int, Float, Double and others support addition operators. Let's see a sample:


var x = 5

let y = 3

print(x + y) // => 8

x += y

print(x) // => 8


x + y performs an arithmetic addition of two integers. Plain and simple.
The expression x += y mutates x variable by appending y to it (same as x = x + y). During this operation x is mutated, so it must declared as a variable with var.

The equivalent methods of addition operators are adding(_:) and the mutating add(_:). These methods are available for Float and Double, but not for Int.
Let's see them in action:


var p = 5.0

let r = 3.0

print(p.adding(r)) // => 8.0

p.add(r)

print(p) // => 8.0


p and r are Double type.
The invocation of p.adding(r) is the same as p + r. Respectively p.add(r) mutates p and is equivalent to p += r.

2. Concatenate strings

The addition and addition assignment operators can perform strings concatenation. For instance, "abc" + "def" creates a string "abcdef".

Let's see an example:


var message = "Hello "

let name = "Batman"

print(message + name) // => "Hello Batman"

message += name

print(message) // => "Hello Batman"


message + name concatenates two strings.
The statement message += name also performs a concatenation. It modifies message in place by appending to its end name string.

You can also use equivalent methods appending(_:) and mutating append(_:), which are more verbose. Let's transform the above example:


var message = "Hello "

let name = "Batman"

print(message.appending(name)) // => "Hello Batman"

message.append(name)

print(message) // => "Hello Batman"


The invocation message.appending(name) concatenates message and name, returning the result. message variable is not modified.
The invocation message.append(name) is mutating the message variable and appends to its end name string.

3. Concatenate arrays

Addition operators are useful to concatenate arrays. [val1, val2] + [val3] creates [val1, val2, val3].

The concatenated arrays must have elements of the same type.


var colors = ["white"]

let darkColors = ["black", "gray"]

print(colors + darkColors) // => ["white", "black", "gray"]

colors += darkColors

print(colors) // => ["white", "black", "gray"]


The expression colors + darkColors creates a new array that contains elements from colors followed by elements from darkColors.
colors += darkColors mutates the colors array in place, by adding to its tail elements from darkColors.

Alternatively you can use the mutating append(contentsOf:_), which is an equivalent of addition assignment operator (+=). Transforming the above example:


var colors = ["white"]

let darkColors = ["black", "gray"]

colors.append(contentsOf: darkColors)

print(colors) // => ["white", "black", "gray"]


The invocation of colors.append(contentsOf: darkColors) modifies colors in place and appends the elements of darkColors.

4. Add time interval to a date

The addition operator enables expressively to add intervals to a Date. The expression date + timeInterval creates a new Date with a specified amount of time added to it. The addition assignment modifies the date in place date += timeInterval.

Let's see how it can be done:


import Foundation

let interval: TimeInterval = 60 * 60 * 24

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd"

if let date = dateFormatter.date(from: "2017-02-15") {

let dayAfter = date + interval

print(dateFormatter.string(from: dayAfter)) // => 2017-02-16

}


oneDay is an interval that contains the number of seconds in 24 hours. dateFormatter creates a date for 2017-02-15.
The expression date + oneDay evaluates to a new date dayAfterDate that is created from date with oneDay time interval added to it.

If you want to modify date directly, make it a variable and use addition assignment operator +=:


/* ... */

if var date = dateFormatter.date(from: "2017-02-15") {

date += interval

print(dateFormatter.string(from: date)) // => 2017-02-16

}


date =+ oneDay mutates date by adding oneDay seconds to it.

The Date methods that provide the same behavior are addingTimeInterval(_:) and the mutating addTimeInterval(_:).

Tip about calendar

The provided way to modify a date adjusts absolute values. You may have unexpected results when adding longer time intervals like weeks or months.

Most of the times Calendar usage is preferable. It provides accurate date modifications according to daylight saving time, months with different numbers of days, and so on.

Let's update the above example and use a calendar instance Calendar.current:


import Foundation

let interval = 60 * 60 * 24

let dateFormatter = DateFormatter()

dateFormatter.dateFormat = "yyyy-MM-dd"

if let date = dateFormatter.date(from: "2017-02-15") {

let calendar = Calendar.current

let dayAfter =

calendar.date(byAdding: .second, value: interval, to: date)!

print(dateFormatter.string(from: dayAfter)) // => 2017-02-16

}


5. Sum measurements

A recent Foundation update introduced measurements and units. It allows to represent distances (for instance 10 miles, 12 kilometers), weights (8 kg) and more.

The good part is that Measurement structure overloads + operator (and additionally * - / < ==). This makes measurement manipulations easy and concise.

Let's sum two distances in kilometers:


import Foundation

let morningRun = Measurement(value: 3, unit: UnitLength.kilometers)

let eveningRun = Measurement(value: 5, unit: UnitLength.kilometers)

let dailyRun = morningRun + eveningRun

print(dailyRun) // => '8000.0 m'


morningRun and eveningRun describe the distance someone ran in the morning and evening.
Plain and simple the addition operator is used to find the daily run distance: morningRun + eveningRun.

The addition operation must sum measurements that describe the same type of physical units (length, mass, speed and more).

For instance, it doesn't make sense to sum speed and mass values. In such case Swift triggers an error:


import Foundation

let turtleSpeed = Measurement(value: 3, unit: UnitLength.kilometers)

let turtleWeight = Measurement(value: 100, unit: UnitMass.grams)

print(turtleSpeed + turtleWeight)

// Error: binary operator '+' cannot be applied to operands of

// type 'Measurement<UnitLength>' and 'Measurement<UnitMass>'


turtleSpeed and turtleWeight are measurements that holds different type of units: UnitLength.kilometers and UnitMass.grams. These are not compatible, and as result Swift triggers an error.

Measurement structure does not provide methods for manipulation. In this case you have to use operators only.
In my opinion it's a nice decision, because operators fits good with measurements.

6. Conclusion

As seen, the addition and addition assignment operators provide short and concise syntax.

Generally these are used to sum numbers and concatenate strings.

You can also benefit from a concise syntax when concatenating arrays, manipulating dates and sum measurements.

Do you know other Swift types that implement addition operator overloading? Feel free to write a comment below!