Avav Smith

Avav Smith

1566881849

Top 12 Array Functions In PHP

Array is collection of similar datatype values. One array can contain set diffrent of values. Three type of array are available first is indexed, associative, and multidimensional arrays in PHP.

PHP Intro

Now the new version of php is 7.3 launch with many features and bugs improvent(fixed). PHP is most popular progmming lanugage in world. PHP is know as Hypertext Preprocessor. The initiative was the name person home page. Most websites and web apps are developed. It is a server side scripting language. PHP script is excute only server side. It is used to develop Static websites pages or Dynamic websites pages or Web applications

PHP latest version 7.3 new features like :

Flexible Heredoc and Nowdoc Syntax

PCRE2 Migration

Multiple MBString Improvements

LDAP Controls Support

Improved FPM Logging

Windows File Deletion Improvements

Several Deprecations

Array()

This is simple array function.

<?php
 $mobile=array("Samsung","MI","Lenovo"); 
 echo "I like " . $mobile[0] . ", " . $mobile[1] . " & " . $mobile[2] . ".";
?>

Array Unique

As the name suggest array unique function is remove duplicate value in an array.

<?php
$a=array("a"=>"56","b"=>"50","c"=>"56");
print_r(array_unique($a));
 ?>

Array Difference

This array_diff () function is used know difference between two or more arrays.

<?php
 $a1=array("1"=>"banana","2"=>"apple","3"=>"orange","4"=>"fruits");
 $a2=array("1"=>"banana","2"=>"apple","3"=>"fruits");
 $result=array_diff($a1,$a2);
 print_r($result);
 ?>

Array Merge

Array_merge() is used to merge two or more array to one array

<?php  
 $a1=array("1"=>"banana","2"=>"apple");
 $a2=array("1"=>"grapes","2"=>"fruits");
 $result=array_merge($a1,$a2);
 print_r($result);
?> 

Array Random

This function is used to generate random keys from array.

<?php
 $a=array("100","200","500","6000","7000");
 $random_keys=array_rand($a,4);
 echo $a[$random_keys[0]]."<br>";
 echo $a[$random_keys[1]]."<br>";
 echo $a[$random_keys[2]]."<br>";
 echo $a[$random_keys[3]];
 ?>

Array Replace

array_replace() function is used to replace the value of arrays.

<?php
 $a1=array("500","560");
 $a2=array("1000","2000");
 print_r(array_replace($a1,$a2));
 ?>

Array Reverse

This Array reserse function is reverse the order of array.

<?php
 $a=array("a"=>"Volvo","b"=>"BMW","c"=>"Toyota");
 print_r(array_reverse($a));
 ?>

Array Search

This function is used to search a value in array.

<?php
 $a=array("a"=>"red","b"=>"green","c"=>"blue");
 echo array_search("red",$a);
 ?>

Array Sum

Array_sum function is used to sum of all value in array.

<?php
 $a=array(25,50,75);
 echo array_sum($a);
 ?>

Array Chunk

This array chunk function is mostly used to split an array to chunks.

 <?php 
 $cars=array("Volvo","BMW","Toyota","Honda","Mercedes","Farari");
 print_r(array_chunk($cars,2));
 ?>

Array Pop

The Array Pop function used to remove element of array.

<?php 
 $a=array("5","10","15");
 array_pop($a);
 print_r($a);
 ?>

Array Push

The Array Push function used to add new element of array.

<?php 
 $a=array("10","15","20");
 array_pop($a);
 print_r($a);
 ?>

Conclusion

Today we have discussed php array functions.

If you have any questions or thoughts to share, use the comment form below to reach us

Recommended Reading

Putting a Laravel App into Production

Why we use Laravel & Wink

Laravel HATEOAS Package

Building PHP apps using SQL Server on Windows

Laravel 5.8 Tutorial - Datatables Individual Column Searching using Ajax

Image Upload Tutorial with Laravel

10 PHP String Functions for every Web Developer

Laravel Performance Optimization: Guide to a Perfect Laravel Developer

#php

What is GEEK

Buddha Community

Top 12 Array Functions In PHP

How to Create Arrays in Python

In this tutorial, you'll know the basics of how to create arrays in Python using the array module. Learn how to use Python arrays. You'll see how to define them and the different methods commonly used for performing operations on them.

This tutorialvideo on 'Arrays in Python' will help you establish a strong hold on all the fundamentals in python programming language. Below are the topics covered in this video:  
1:15 What is an array?
2:53 Is python list same as an array?
3:48  How to create arrays in python?
7:19 Accessing array elements
9:59 Basic array operations
        - 10:33  Finding the length of an array
        - 11:44  Adding Elements
        - 15:06  Removing elements
        - 18:32  Array concatenation
       - 20:59  Slicing
       - 23:26  Looping  


Python Array Tutorial – Define, Index, Methods

In this article, you'll learn how to use Python arrays. You'll see how to define them and the different methods commonly used for performing operations on them.

The artcile covers arrays that you create by importing the array module. We won't cover NumPy arrays here.

Table of Contents

  1. Introduction to Arrays
    1. The differences between Lists and Arrays
    2. When to use arrays
  2. How to use arrays
    1. Define arrays
    2. Find the length of arrays
    3. Array indexing
    4. Search through arrays
    5. Loop through arrays
    6. Slice an array
  3. Array methods for performing operations
    1. Change an existing value
    2. Add a new value
    3. Remove a value
  4. Conclusion

Let's get started!

What are Python Arrays?

Arrays are a fundamental data structure, and an important part of most programming languages. In Python, they are containers which are able to store more than one item at the same time.

Specifically, they are an ordered collection of elements with every value being of the same data type. That is the most important thing to remember about Python arrays - the fact that they can only hold a sequence of multiple items that are of the same type.

What's the Difference between Python Lists and Python Arrays?

Lists are one of the most common data structures in Python, and a core part of the language.

Lists and arrays behave similarly.

Just like arrays, lists are an ordered sequence of elements.

They are also mutable and not fixed in size, which means they can grow and shrink throughout the life of the program. Items can be added and removed, making them very flexible to work with.

However, lists and arrays are not the same thing.

Lists store items that are of various data types. This means that a list can contain integers, floating point numbers, strings, or any other Python data type, at the same time. That is not the case with arrays.

As mentioned in the section above, arrays store only items that are of the same single data type. There are arrays that contain only integers, or only floating point numbers, or only any other Python data type you want to use.

When to Use Python Arrays

Lists are built into the Python programming language, whereas arrays aren't. Arrays are not a built-in data structure, and therefore need to be imported via the array module in order to be used.

Arrays of the array module are a thin wrapper over C arrays, and are useful when you want to work with homogeneous data.

They are also more compact and take up less memory and space which makes them more size efficient compared to lists.

If you want to perform mathematical calculations, then you should use NumPy arrays by importing the NumPy package. Besides that, you should just use Python arrays when you really need to, as lists work in a similar way and are more flexible to work with.

How to Use Arrays in Python

In order to create Python arrays, you'll first have to import the array module which contains all the necassary functions.

There are three ways you can import the array module:

  • By using import array at the top of the file. This includes the module array. You would then go on to create an array using array.array().
import array

#how you would create an array
array.array()
  • Instead of having to type array.array() all the time, you could use import array as arr at the top of the file, instead of import array alone. You would then create an array by typing arr.array(). The arr acts as an alias name, with the array constructor then immediately following it.
import array as arr

#how you would create an array
arr.array()
  • Lastly, you could also use from array import *, with * importing all the functionalities available. You would then create an array by writing the array() constructor alone.
from array import *

#how you would create an array
array()

How to Define Arrays in Python

Once you've imported the array module, you can then go on to define a Python array.

The general syntax for creating an array looks like this:

variable_name = array(typecode,[elements])

Let's break it down:

  • variable_name would be the name of the array.
  • The typecode specifies what kind of elements would be stored in the array. Whether it would be an array of integers, an array of floats or an array of any other Python data type. Remember that all elements should be of the same data type.
  • Inside square brackets you mention the elements that would be stored in the array, with each element being separated by a comma. You can also create an empty array by just writing variable_name = array(typecode) alone, without any elements.

Below is a typecode table, with the different typecodes that can be used with the different data types when defining Python arrays:

TYPECODEC TYPEPYTHON TYPESIZE
'b'signed charint1
'B'unsigned charint1
'u'wchar_tUnicode character2
'h'signed shortint2
'H'unsigned shortint2
'i'signed intint2
'I'unsigned intint2
'l'signed longint4
'L'unsigned longint4
'q'signed long longint8
'Q'unsigned long longint8
'f'floatfloat4
'd'doublefloat8

Tying everything together, here is an example of how you would define an array in Python:

import array as arr 

numbers = arr.array('i',[10,20,30])


print(numbers)

#output

#array('i', [10, 20, 30])

Let's break it down:

  • First we included the array module, in this case with import array as arr .
  • Then, we created a numbers array.
  • We used arr.array() because of import array as arr .
  • Inside the array() constructor, we first included i, for signed integer. Signed integer means that the array can include positive and negative values. Unsigned integer, with H for example, would mean that no negative values are allowed.
  • Lastly, we included the values to be stored in the array in square brackets.

Keep in mind that if you tried to include values that were not of i typecode, meaning they were not integer values, you would get an error:

import array as arr 

numbers = arr.array('i',[10.0,20,30])


print(numbers)

#output

#Traceback (most recent call last):
# File "/Users/dionysialemonaki/python_articles/demo.py", line 14, in <module>
#   numbers = arr.array('i',[10.0,20,30])
#TypeError: 'float' object cannot be interpreted as an integer

In the example above, I tried to include a floating point number in the array. I got an error because this is meant to be an integer array only.

Another way to create an array is the following:

from array import *

#an array of floating point values
numbers = array('d',[10.0,20.0,30.0])

print(numbers)

#output

#array('d', [10.0, 20.0, 30.0])

The example above imported the array module via from array import * and created an array numbers of float data type. This means that it holds only floating point numbers, which is specified with the 'd' typecode.

How to Find the Length of an Array in Python

To find out the exact number of elements contained in an array, use the built-in len() method.

It will return the integer number that is equal to the total number of elements in the array you specify.

import array as arr 

numbers = arr.array('i',[10,20,30])


print(len(numbers))

#output
# 3

In the example above, the array contained three elements – 10, 20, 30 – so the length of numbers is 3.

Array Indexing and How to Access Individual Items in an Array in Python

Each item in an array has a specific address. Individual items are accessed by referencing their index number.

Indexing in Python, and in all programming languages and computing in general, starts at 0. It is important to remember that counting starts at 0 and not at 1.

To access an element, you first write the name of the array followed by square brackets. Inside the square brackets you include the item's index number.

The general syntax would look something like this:

array_name[index_value_of_item]

Here is how you would access each individual element in an array:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[0]) # gets the 1st element
print(numbers[1]) # gets the 2nd element
print(numbers[2]) # gets the 3rd element

#output

#10
#20
#30

Remember that the index value of the last element of an array is always one less than the length of the array. Where n is the length of the array, n - 1 will be the index value of the last item.

Note that you can also access each individual element using negative indexing.

With negative indexing, the last element would have an index of -1, the second to last element would have an index of -2, and so on.

Here is how you would get each item in an array using that method:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[-1]) #gets last item
print(numbers[-2]) #gets second to last item
print(numbers[-3]) #gets first item
 
#output

#30
#20
#10

How to Search Through an Array in Python

You can find out an element's index number by using the index() method.

You pass the value of the element being searched as the argument to the method, and the element's index number is returned.

import array as arr 

numbers = arr.array('i',[10,20,30])

#search for the index of the value 10
print(numbers.index(10))

#output

#0

If there is more than one element with the same value, the index of the first instance of the value will be returned:

import array as arr 


numbers = arr.array('i',[10,20,30,10,20,30])

#search for the index of the value 10
#will return the index number of the first instance of the value 10
print(numbers.index(10))

#output

#0

How to Loop through an Array in Python

You've seen how to access each individual element in an array and print it out on its own.

You've also seen how to print the array, using the print() method. That method gives the following result:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers)

#output

#array('i', [10, 20, 30])

What if you want to print each value one by one?

This is where a loop comes in handy. You can loop through the array and print out each value, one-by-one, with each loop iteration.

For this you can use a simple for loop:

import array as arr 

numbers = arr.array('i',[10,20,30])

for number in numbers:
    print(number)
    
#output
#10
#20
#30

You could also use the range() function, and pass the len() method as its parameter. This would give the same result as above:

import array as arr  

values = arr.array('i',[10,20,30])

#prints each individual value in the array
for value in range(len(values)):
    print(values[value])

#output

#10
#20
#30

How to Slice an Array in Python

To access a specific range of values inside the array, use the slicing operator, which is a colon :.

When using the slicing operator and you only include one value, the counting starts from 0 by default. It gets the first item, and goes up to but not including the index number you specify.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#get the values 10 and 20 only
print(numbers[:2])  #first to second position

#output

#array('i', [10, 20])

When you pass two numbers as arguments, you specify a range of numbers. In this case, the counting starts at the position of the first number in the range, and up to but not including the second one:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])


#get the values 20 and 30 only
print(numbers[1:3]) #second to third position

#output

#rray('i', [20, 30])

Methods For Performing Operations on Arrays in Python

Arrays are mutable, which means they are changeable. You can change the value of the different items, add new ones, or remove any you don't want in your program anymore.

Let's see some of the most commonly used methods which are used for performing operations on arrays.

How to Change the Value of an Item in an Array

You can change the value of a specific element by speficying its position and assigning it a new value:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#change the first element
#change it from having a value of 10 to having a value of 40
numbers[0] = 40

print(numbers)

#output

#array('i', [40, 20, 30])

How to Add a New Value to an Array

To add one single value at the end of an array, use the append() method:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40)

print(numbers)

#output

#array('i', [10, 20, 30, 40])

Be aware that the new item you add needs to be the same data type as the rest of the items in the array.

Look what happens when I try to add a float to an array of integers:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40.0)

print(numbers)

#output

#Traceback (most recent call last):
#  File "/Users/dionysialemonaki/python_articles/demo.py", line 19, in <module>
#   numbers.append(40.0)
#TypeError: 'float' object cannot be interpreted as an integer

But what if you want to add more than one value to the end an array?

Use the extend() method, which takes an iterable (such as a list of items) as an argument. Again, make sure that the new items are all the same data type.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integers 40,50,60 to the end of numbers
#The numbers need to be enclosed in square brackets

numbers.extend([40,50,60])

print(numbers)

#output

#array('i', [10, 20, 30, 40, 50, 60])

And what if you don't want to add an item to the end of an array? Use the insert() method, to add an item at a specific position.

The insert() function takes two arguments: the index number of the position the new element will be inserted, and the value of the new element.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 in the first position
#remember indexing starts at 0

numbers.insert(0,40)

print(numbers)

#output

#array('i', [40, 10, 20, 30])

How to Remove a Value from an Array

To remove an element from an array, use the remove() method and include the value as an argument to the method.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30])

With remove(), only the first instance of the value you pass as an argument will be removed.

See what happens when there are more than one identical values:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Only the first occurence of 10 is removed.

You can also use the pop() method, and specify the position of the element to be removed:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

#remove the first instance of 10
numbers.pop(0)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Conclusion

And there you have it - you now know the basics of how to create arrays in Python using the array module. Hopefully you found this guide helpful.

Thanks for reading and happy coding!

#python #programming 

Connor Mills

Connor Mills

1670560264

Understanding Arrays in Python

Learn how to use Python arrays. Create arrays in Python using the array module. You'll see how to define them and the different methods commonly used for performing operations on them.
 

The artcile covers arrays that you create by importing the array module. We won't cover NumPy arrays here.

Table of Contents

  1. Introduction to Arrays
    1. The differences between Lists and Arrays
    2. When to use arrays
  2. How to use arrays
    1. Define arrays
    2. Find the length of arrays
    3. Array indexing
    4. Search through arrays
    5. Loop through arrays
    6. Slice an array
  3. Array methods for performing operations
    1. Change an existing value
    2. Add a new value
    3. Remove a value
  4. Conclusion

Let's get started!


What are Python Arrays?

Arrays are a fundamental data structure, and an important part of most programming languages. In Python, they are containers which are able to store more than one item at the same time.

Specifically, they are an ordered collection of elements with every value being of the same data type. That is the most important thing to remember about Python arrays - the fact that they can only hold a sequence of multiple items that are of the same type.

What's the Difference between Python Lists and Python Arrays?

Lists are one of the most common data structures in Python, and a core part of the language.

Lists and arrays behave similarly.

Just like arrays, lists are an ordered sequence of elements.

They are also mutable and not fixed in size, which means they can grow and shrink throughout the life of the program. Items can be added and removed, making them very flexible to work with.

However, lists and arrays are not the same thing.

Lists store items that are of various data types. This means that a list can contain integers, floating point numbers, strings, or any other Python data type, at the same time. That is not the case with arrays.

As mentioned in the section above, arrays store only items that are of the same single data type. There are arrays that contain only integers, or only floating point numbers, or only any other Python data type you want to use.

When to Use Python Arrays

Lists are built into the Python programming language, whereas arrays aren't. Arrays are not a built-in data structure, and therefore need to be imported via the array module in order to be used.

Arrays of the array module are a thin wrapper over C arrays, and are useful when you want to work with homogeneous data.

They are also more compact and take up less memory and space which makes them more size efficient compared to lists.

If you want to perform mathematical calculations, then you should use NumPy arrays by importing the NumPy package. Besides that, you should just use Python arrays when you really need to, as lists work in a similar way and are more flexible to work with.

How to Use Arrays in Python

In order to create Python arrays, you'll first have to import the array module which contains all the necassary functions.

There are three ways you can import the array module:

  1. By using import array at the top of the file. This includes the module array. You would then go on to create an array using array.array().
import array

#how you would create an array
array.array()
  1. Instead of having to type array.array() all the time, you could use import array as arr at the top of the file, instead of import array alone. You would then create an array by typing arr.array(). The arr acts as an alias name, with the array constructor then immediately following it.
import array as arr

#how you would create an array
arr.array()
  1. Lastly, you could also use from array import *, with * importing all the functionalities available. You would then create an array by writing the array() constructor alone.
from array import *

#how you would create an array
array()

How to Define Arrays in Python

Once you've imported the array module, you can then go on to define a Python array.

The general syntax for creating an array looks like this:

variable_name = array(typecode,[elements])

Let's break it down:

  • variable_name would be the name of the array.
  • The typecode specifies what kind of elements would be stored in the array. Whether it would be an array of integers, an array of floats or an array of any other Python data type. Remember that all elements should be of the same data type.
  • Inside square brackets you mention the elements that would be stored in the array, with each element being separated by a comma. You can also create an empty array by just writing variable_name = array(typecode) alone, without any elements.

Below is a typecode table, with the different typecodes that can be used with the different data types when defining Python arrays:

TYPECODEC TYPEPYTHON TYPESIZE
'b'signed charint1
'B'unsigned charint1
'u'wchar_tUnicode character2
'h'signed shortint2
'H'unsigned shortint2
'i'signed intint2
'I'unsigned intint2
'l'signed longint4
'L'unsigned longint4
'q'signed long longint8
'Q'unsigned long longint8
'f'floatfloat4
'd'doublefloat8

Tying everything together, here is an example of how you would define an array in Python:

import array as arr 

numbers = arr.array('i',[10,20,30])


print(numbers)

#output

#array('i', [10, 20, 30])

Let's break it down:

  • First we included the array module, in this case with import array as arr .
  • Then, we created a numbers array.
  • We used arr.array() because of import array as arr .
  • Inside the array() constructor, we first included i, for signed integer. Signed integer means that the array can include positive and negative values. Unsigned integer, with H for example, would mean that no negative values are allowed.
  • Lastly, we included the values to be stored in the array in square brackets.

Keep in mind that if you tried to include values that were not of i typecode, meaning they were not integer values, you would get an error:

import array as arr 

numbers = arr.array('i',[10.0,20,30])


print(numbers)

#output

#Traceback (most recent call last):
# File "/Users/dionysialemonaki/python_articles/demo.py", line 14, in <module>
#   numbers = arr.array('i',[10.0,20,30])
#TypeError: 'float' object cannot be interpreted as an integer

In the example above, I tried to include a floating point number in the array. I got an error because this is meant to be an integer array only.

Another way to create an array is the following:

from array import *

#an array of floating point values
numbers = array('d',[10.0,20.0,30.0])

print(numbers)

#output

#array('d', [10.0, 20.0, 30.0])

The example above imported the array module via from array import * and created an array numbers of float data type. This means that it holds only floating point numbers, which is specified with the 'd' typecode.

How to Find the Length of an Array in Python

To find out the exact number of elements contained in an array, use the built-in len() method.

It will return the integer number that is equal to the total number of elements in the array you specify.

import array as arr 

numbers = arr.array('i',[10,20,30])


print(len(numbers))

#output
# 3

In the example above, the array contained three elements – 10, 20, 30 – so the length of numbers is 3.

Array Indexing and How to Access Individual Items in an Array in Python

Each item in an array has a specific address. Individual items are accessed by referencing their index number.

Indexing in Python, and in all programming languages and computing in general, starts at 0. It is important to remember that counting starts at 0 and not at 1.

To access an element, you first write the name of the array followed by square brackets. Inside the square brackets you include the item's index number.

The general syntax would look something like this:

array_name[index_value_of_item]

Here is how you would access each individual element in an array:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[0]) # gets the 1st element
print(numbers[1]) # gets the 2nd element
print(numbers[2]) # gets the 3rd element

#output

#10
#20
#30

Remember that the index value of the last element of an array is always one less than the length of the array. Where n is the length of the array, n - 1 will be the index value of the last item.

Note that you can also access each individual element using negative indexing.

With negative indexing, the last element would have an index of -1, the second to last element would have an index of -2, and so on.

Here is how you would get each item in an array using that method:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers[-1]) #gets last item
print(numbers[-2]) #gets second to last item
print(numbers[-3]) #gets first item
 
#output

#30
#20
#10

How to Search Through an Array in Python

You can find out an element's index number by using the index() method.

You pass the value of the element being searched as the argument to the method, and the element's index number is returned.

import array as arr 

numbers = arr.array('i',[10,20,30])

#search for the index of the value 10
print(numbers.index(10))

#output

#0

If there is more than one element with the same value, the index of the first instance of the value will be returned:

import array as arr 


numbers = arr.array('i',[10,20,30,10,20,30])

#search for the index of the value 10
#will return the index number of the first instance of the value 10
print(numbers.index(10))

#output

#0

How to Loop through an Array in Python

You've seen how to access each individual element in an array and print it out on its own.

You've also seen how to print the array, using the print() method. That method gives the following result:

import array as arr 

numbers = arr.array('i',[10,20,30])

print(numbers)

#output

#array('i', [10, 20, 30])

What if you want to print each value one by one?

This is where a loop comes in handy. You can loop through the array and print out each value, one-by-one, with each loop iteration.

For this you can use a simple for loop:

import array as arr 

numbers = arr.array('i',[10,20,30])

for number in numbers:
    print(number)
    
#output
#10
#20
#30

You could also use the range() function, and pass the len() method as its parameter. This would give the same result as above:

import array as arr  

values = arr.array('i',[10,20,30])

#prints each individual value in the array
for value in range(len(values)):
    print(values[value])

#output

#10
#20
#30

How to Slice an Array in Python

To access a specific range of values inside the array, use the slicing operator, which is a colon :.

When using the slicing operator and you only include one value, the counting starts from 0 by default. It gets the first item, and goes up to but not including the index number you specify.


import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#get the values 10 and 20 only
print(numbers[:2])  #first to second position

#output

#array('i', [10, 20])

When you pass two numbers as arguments, you specify a range of numbers. In this case, the counting starts at the position of the first number in the range, and up to but not including the second one:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])


#get the values 20 and 30 only
print(numbers[1:3]) #second to third position

#output

#rray('i', [20, 30])

Methods For Performing Operations on Arrays in Python

Arrays are mutable, which means they are changeable. You can change the value of the different items, add new ones, or remove any you don't want in your program anymore.

Let's see some of the most commonly used methods which are used for performing operations on arrays.

How to Change the Value of an Item in an Array

You can change the value of a specific element by speficying its position and assigning it a new value:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#change the first element
#change it from having a value of 10 to having a value of 40
numbers[0] = 40

print(numbers)

#output

#array('i', [40, 20, 30])

How to Add a New Value to an Array

To add one single value at the end of an array, use the append() method:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40)

print(numbers)

#output

#array('i', [10, 20, 30, 40])

Be aware that the new item you add needs to be the same data type as the rest of the items in the array.

Look what happens when I try to add a float to an array of integers:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 to the end of numbers
numbers.append(40.0)

print(numbers)

#output

#Traceback (most recent call last):
#  File "/Users/dionysialemonaki/python_articles/demo.py", line 19, in <module>
#   numbers.append(40.0)
#TypeError: 'float' object cannot be interpreted as an integer

But what if you want to add more than one value to the end an array?

Use the extend() method, which takes an iterable (such as a list of items) as an argument. Again, make sure that the new items are all the same data type.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integers 40,50,60 to the end of numbers
#The numbers need to be enclosed in square brackets

numbers.extend([40,50,60])

print(numbers)

#output

#array('i', [10, 20, 30, 40, 50, 60])

And what if you don't want to add an item to the end of an array? Use the insert() method, to add an item at a specific position.

The insert() function takes two arguments: the index number of the position the new element will be inserted, and the value of the new element.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

#add the integer 40 in the first position
#remember indexing starts at 0

numbers.insert(0,40)

print(numbers)

#output

#array('i', [40, 10, 20, 30])

How to Remove a Value from an Array

To remove an element from an array, use the remove() method and include the value as an argument to the method.

import array as arr 

#original array
numbers = arr.array('i',[10,20,30])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30])

With remove(), only the first instance of the value you pass as an argument will be removed.

See what happens when there are more than one identical values:


import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

numbers.remove(10)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Only the first occurence of 10 is removed.

You can also use the pop() method, and specify the position of the element to be removed:

import array as arr 

#original array
numbers = arr.array('i',[10,20,30,10,20])

#remove the first instance of 10
numbers.pop(0)

print(numbers)

#output

#array('i', [20, 30, 10, 20])

Conclusion

And there you have it - you now know the basics of how to create arrays in Python using the array module. Hopefully you found this guide helpful.

You'll start from the basics and learn in an interacitve and beginner-friendly way. You'll also build five projects at the end to put into practice and help reinforce what you learned.

Thanks for reading and happy coding!

Original article source at https://www.freecodecamp.org

#python 

A Collection Of Swift Tips & Tricks That I've Shared on Twitter

⚠️ This list is no longer being updated. For my latest Swift tips, checkout the "Tips" section on Swift by Sundell.

Swift tips & tricks ⚡️

One of the things I really love about Swift is how I keep finding interesting ways to use it in various situations, and when I do - I usually share them on Twitter. Here's a collection of all the tips & tricks that I've shared so far. Each entry has a link to the original tweet, if you want to respond with some feedback or question, which is always super welcome! 🚀

Also make sure to check out all of my other Swift content:

#102 Making async tests faster and more stable

🚀 Here are some quick tips to make async tests faster & more stable:

  • 😴 Avoid sleep() - use expectations instead
  • ⏱ Use generous timeouts to avoid flakiness on CI
  • 🧐 Put all assertions at the end of each test, not inside closures
// BEFORE:

class MentionDetectorTests: XCTestCase {
    func testDetectingMention() {
        let detector = MentionDetector()
        let string = "This test was written by @johnsundell."

        detector.detectMentions(in: string) { mentions in
            XCTAssertEqual(mentions, ["johnsundell"])
        }
        
        sleep(2)
    }
}

// AFTER:

class MentionDetectorTests: XCTestCase {
    func testDetectingMention() {
        let detector = MentionDetector()
        let string = "This test was written by @johnsundell."

        var mentions: [String]?
        let expectation = self.expectation(description: #function)

        detector.detectMentions(in: string) {
            mentions = $0
            expectation.fulfill()
        }

        waitForExpectations(timeout: 10)
        XCTAssertEqual(mentions, ["johnsundell"])
    }
}

For more on async testing, check out "Unit testing asynchronous Swift code".

#101 Adding support for Apple Pencil double-taps

✍️ Adding support for the new Apple Pencil double-tap feature is super easy! All you have to do is to create a UIPencilInteraction, add it to a view, and implement one delegate method. Hopefully all pencil-compatible apps will soon adopt this.

let interaction = UIPencilInteraction()
interaction.delegate = self
view.addInteraction(interaction)

extension ViewController: UIPencilInteractionDelegate {
    func pencilInteractionDidTap(_ interaction: UIPencilInteraction) {
        // Handle pencil double-tap
    }
}

For more on using this and other iPad Pro features, check out "Building iPad Pro features in Swift".

#100 Combining values with functions

😎 Here's a cool function that combines a value with a function to return a closure that captures that value, so that it can be called without any arguments. Super useful when working with closure-based APIs and we want to use some of our properties without having to capture self.

func combine<A, B>(_ value: A, with closure: @escaping (A) -> B) -> () -> B {
    return { closure(value) }
}

// BEFORE:

class ProductViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        buyButton.handler = { [weak self] in
            guard let self = self else {
                return
            }
            
            self.productManager.startCheckout(for: self.product)
        }
    }
}

// AFTER:

class ProductViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        buyButton.handler = combine(product, with: productManager.startCheckout)
    }
}

#99 Dependency injection using functions

💉 When I'm only using a single function from a dependency, I love to inject that function as a closure, instead of having to create a protocol and inject the whole object. Makes dependency injection & testing super simple.

final class ArticleLoader {
    typealias Networking = (Endpoint) -> Future<Data>
    
    private let networking: Networking
    
    init(networking: @escaping Networking = URLSession.shared.load) {
        self.networking = networking
    }
    
    func loadLatest() -> Future<[Article]> {
        return networking(.latestArticles).decode()
    }
}

For more on this technique, check out "Simple Swift dependency injection with functions".

#98 Using a custom exception handler

💥 It's cool that you can easily assign a closure as a custom NSException handler. This is super useful when building things in Playgrounds - since you can't use breakpoints - so instead of just signal SIGABRT, you'll get the full exception description if something goes wrong.

NSSetUncaughtExceptionHandler { exception in
    print(exception)
}

#97 Using type aliases to give semantic meaning to primitives

❤️ I love that in Swift, we can use the type system to make our code so much more self-documenting - one way of doing so is to use type aliases to give the primitive types that we use a more semantic meaning.

extension List.Item {
    // Using type aliases, we can give semantic meaning to the
    // primitive types that we use, without having to introduce
    // wrapper types.
    typealias Index = Int
}

extension List {
    enum Mutation {
        // Our enum cases now become a lot more self-documenting,
        // without having to add additional parameter labels to
        // explain them.
        case add(Item, Item.Index)
        case update(Item, Item.Index)
        case remove(Item.Index)
    }
}

For more on self-documenting code, check out "Writing self-documenting Swift code".

#96 Specializing protocols using constraints

🤯 A little late night prototyping session reveals that protocol constraints can not only be applied to extensions - they can also be added to protocol definitions!

This is awesome, since it lets us easily define specialized protocols based on more generic ones.

protocol Component {
    associatedtype Container
    func add(to container: Container)
}

// Protocols that inherit from other protocols can include
// constraints to further specialize them.
protocol ViewComponent: Component where Container == UIView {
    associatedtype View: UIView
    var view: View { get }
}

extension ViewComponent {
    func add(to container: UIView) {
        container.addSubview(view)
    }
}

For more on specializing protocols, check out "Specializing protocols in Swift".

#95 Unwrapping an optional or throwing an error

📦 Here's a super handy extension on Swift's Optional type, which gives us a really nice API for easily unwrapping an optional, or throwing an error in case the value turned out to be nil:

extension Optional {
    func orThrow(_ errorExpression: @autoclosure () -> Error) throws -> Wrapped {
        switch self {
        case .some(let value):
            return value
        case .none:
            throw errorExpression()
        }
    }
}

let file = try loadFile(at: path).orThrow(MissingFileError())

For more ways that optionals can be extended, check out "Extending optionals in Swift".

#94 Testing code that uses static APIs

👩‍🔬 Testing code that uses static APIs can be really tricky, but there's a way that it can often be done - using Swift's first class function capabilities!

Instead of accessing that static API directly, we can inject the function we want to use, which enables us to mock it!

// BEFORE

class FriendsLoader {
    func loadFriends(then handler: @escaping (Result<[Friend]>) -> Void) {
        Networking.loadData(from: .friends) { result in
            ...
        }
    }
}

// AFTER

class FriendsLoader {
    typealias Handler<T> = (Result<T>) -> Void
    typealias DataLoadingFunction = (Endpoint, @escaping Handler<Data>) -> Void

    func loadFriends(using dataLoading: DataLoadingFunction = Networking.loadData,
                     then handler: @escaping Handler<[Friend]>) {
        dataLoading(.friends) { result in
            ...
        }
    }
}

// MOCKING IN TESTS

let dataLoading: FriendsLoader.DataLoadingFunction = { _, handler in
    handler(.success(mockData))
}

friendsLoader.loadFriends(using: dataLoading) { result in
    ...
}

#93 Matching multiple enum cases with associated values

🐾 Swift's pattern matching capabilities are so powerful! Two enum cases with associated values can even be matched and handled by the same switch case - which is super useful when handling state changes with similar data.

enum DownloadState {
    case inProgress(progress: Double)
    case paused(progress: Double)
    case cancelled
    case finished(Data)
}

func downloadStateDidChange(to state: DownloadState) {
    switch state {
    case .inProgress(let progress), .paused(let progress):
        updateProgressView(with: progress)
    case .cancelled:
        showCancelledMessage()
    case .finished(let data):
        process(data)
    }
}

#92 Multiline string literals

🅰 One really nice benefit of Swift multiline string literals - even for single lines of text - is that they don't require quotes to be escaped. Perfect when working with things like HTML, or creating a custom description for an object.

let html = highlighter.highlight("Array<String>")

XCTAssertEqual(html, """
<span class="type">Array</span>&lt;<span class="type">String</span>&gt;
""")

#91 Reducing sequences

💎 While it's very common in functional programming, the reduce function might be a bit of a hidden gem in Swift. It provides a super useful way to transform a sequence into a single value.

extension Sequence where Element: Equatable {
    func numberOfOccurrences(of target: Element) -> Int {
        return reduce(0) { result, element in
            guard element == target else {
                return result
            }

            return result + 1
        }
    }
}

You can read more about transforming collections in "Transforming collections in Swift".

#90 Avoiding manual Codable implementations

📦 When I use Codable in Swift, I want to avoid manual implementations as much as possible, even when there's a mismatch between my code structure and the JSON I'm decoding.

One way that can often be achieved is to use private data containers combined with computed properties.

struct User: Codable {
    let name: String
    let age: Int

    var homeTown: String { return originPlace.name }

    private let originPlace: Place
}

private extension User {
    struct Place: Codable {
        let name: String
    }
}

extension User {
    struct Container: Codable {
        let user: User
    }
}

#89 Using feature flags instead of feature branches

🚢 Instead of using feature branches, I merge almost all of my code directly into master - and then I use feature flags to conditionally enable features when they're ready. That way I can avoid merge conflicts and keep shipping!

extension ListViewController {
    func addSearchIfNeeded() {
        // Rather than having to keep maintaining a separate
        // feature branch for a new feature, we can use a flag
        // to conditionally turn it on.
        guard FeatureFlags.searchEnabled else {
            return
        }

        let resultsVC = SearchResultsViewController()
        let searchVC = UISearchController(
            searchResultsController: resultsVC
        )

        searchVC.searchResultsUpdater = resultsVC
        navigationItem.searchController = searchVC
    }
}

You can read more about feature flags in "Feature flags in Swift".

#88 Lightweight data hierarchies using tuples

💾 Here I'm using tuples to create a lightweight hierarchy for my data, giving me a nice structure without having to introduce any additional types.

struct CodeSegment {
    var tokens: (
        previous: String?,
        current: String
    )

    var delimiters: (
        previous: Character?
        next: Character?
    )
}

handle(segment.tokens.current)

You can read more about tuples in "Using tuples as lightweight types in Swift"

#87 The rule of threes

3️⃣ Whenever I have 3 properties or local variables that share the same prefix, I usually try to extract them into their own method or type. That way I can avoid massive types & methods, and also increase readability, without falling into a "premature optimization" trap.

Before

public func generate() throws {
    let contentFolder = try folder.subfolder(named: "content")

    let articleFolder = try contentFolder.subfolder(named: "posts")
    let articleProcessor = ContentProcessor(folder: articleFolder)
    let articles = try articleProcessor.process()

    ...
}

After

public func generate() throws {
    let contentFolder = try folder.subfolder(named: "content")
    let articles = try processArticles(in: contentFolder)
    ...
}

private func processArticles(in folder: Folder) throws -> [ContentItem] {
    let folder = try folder.subfolder(named: "posts")
    let processor = ContentProcessor(folder: folder)
    return try processor.process()
}

#86 Useful Codable extensions

👨‍🔧 Here's two extensions that I always add to the Encodable & Decodable protocols, which for me really make the Codable API nicer to use. By using type inference for decoding, a lot of boilerplate can be removed when the compiler is already able to infer the resulting type.

extension Encodable {
    func encoded() throws -> Data {
        return try JSONEncoder().encode(self)
    }
}

extension Data {
    func decoded<T: Decodable>() throws -> T {
        return try JSONDecoder().decode(T.self, from: self)
    }
}

let data = try user.encoded()

// By using a generic type in the decoded() method, the
// compiler can often infer the type we want to decode
// from the current context.
try userDidLogin(data.decoded())

// And if not, we can always supply the type, still making
// the call site read very nicely.
let otherUser = try data.decoded() as User

#85 Using shared UserDefaults suites

📦 UserDefaults is a lot more powerful than what it first might seem like. Not only can it store more complex values (like dates & dictionaries) and parse command line arguments - it also enables easy sharing of settings & lightweight data between apps in the same App Group.

let sharedDefaults = UserDefaults(suiteName: "my-app-group")!
let useDarkMode = sharedDefaults.bool(forKey: "dark-mode")

// This value is put into the shared suite.
sharedDefaults.set(true, forKey: "dark-mode")

// If you want to treat the shared settings as read-only (and add
// local overrides on top of them), you can simply add the shared
// suite to the standard UserDefaults.
let combinedDefaults = UserDefaults.standard
combinedDefaults.addSuite(named: "my-app-group")

// This value is a local override, not added to the shared suite.
combinedDefaults.set(true, forKey: "app-specific-override")

#84 Custom UIView backing layers

🎨 By overriding layerClass you can tell UIKit what CALayer class to use for a UIView's backing layer. That way you can reduce the amount of layers, and don't have to do any manual layout.

final class GradientView: UIView {
    override class var layerClass: AnyClass { return CAGradientLayer.self }

    var colors: (start: UIColor, end: UIColor)? {
        didSet { updateLayer() }
    }

    private func updateLayer() {
        let layer = self.layer as! CAGradientLayer
        layer.colors = colors.map { [$0.start.cgColor, $0.end.cgColor] }
    }
}

#83 Auto-Equatable enums with associated values

✅ That the compiler now automatically synthesizes Equatable conformances is such a huge upgrade for Swift! And the cool thing is that it works for all kinds of types - even for enums with associated values! Especially useful when using enums for verification in unit tests.

struct Article: Equatable {
    let title: String
    let text: String
}

struct User: Equatable {
    let name: String
    let age: Int
}

extension Navigator {
    enum Destination: Equatable {
        case profile(User)
        case article(Article)
    }
}

func testNavigatingToArticle() {
    let article = Article(title: "Title", text: "Text")
    controller.select(article)
    XCTAssertEqual(navigator.destinations, [.article(article)])
}

#82 Defaults for associated types

🤝 Associated types can have defaults in Swift - which is super useful for types that are not easily inferred (for example when they're not used for a specific instance method or property).

protocol Identifiable {
    associatedtype RawIdentifier: Codable = String

    var id: Identifier<Self> { get }
}

struct User: Identifiable {
    let id: Identifier<User>
    let name: String
}

struct Group: Identifiable {
    typealias RawIdentifier = Int

    let id: Identifier<Group>
    let name: String
}

#81 Creating a dedicated identifier type

🆔 If you want to avoid using plain strings as identifiers (which can increase both type safety & readability), it's really easy to create a custom Identifier type that feels just like a native Swift type, thanks to protocols!

More on this topic in "Type-safe identifiers in Swift".

struct Identifier: Hashable {
    let string: String
}

extension Identifier: ExpressibleByStringLiteral {
    init(stringLiteral value: String) {
        string = value
    }
}

extension Identifier: CustomStringConvertible {
    var description: String {
        return string
    }
}

extension Identifier: Codable {
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        string = try container.decode(String.self)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(string)
    }
}

struct Article: Codable {
    let id: Identifier
    let title: String
}

let article = Article(id: "my-article", title: "Hello world!")

#80 Assigning optional tuple members to variables

🙌 A really cool thing about using tuples to model the internal state of a Swift type, is that you can unwrap an optional tuple's members directly into local variables.

Very useful in order to group multiple optional values together for easy unwrapping & handling.

class ImageTransformer {
    private var queue = [(image: UIImage, transform: Transform)]()

    private func processNext() {
        // When unwrapping an optional tuple, you can assign the members
        // directly to local variables.
        guard let (image, transform) = queue.first else {
            return
        }

        let context = Context()
        context.draw(image)
        context.apply(transform)
        ...
    }
}

#79 Struct convenience initializers

❤️ I love to structure my code using extensions in Swift. One big benefit of doing so when it comes to struct initializers, is that defining a convenience initializer doesn't remove the default one the compiler generates - best of both worlds!

struct Article {
    let date: Date
    var title: String
    var text: String
    var comments: [Comment]
}

extension Article {
    init(title: String, text: String) {
        self.init(date: Date(), title: title, text: text, comments: [])
    }
}

let articleA = Article(title: "Best Cupcake Recipe", text: "...")

let articleB = Article(
    date: Date(),
    title: "Best Cupcake Recipe",
    text: "...",
    comments: [
        Comment(user: currentUser, text: "Yep, can confirm!")
    ]
)

#78 Usages of throwing functions

🏈 A big benefit of using throwing functions for synchronous Swift APIs is that the caller can decide whether they want to treat the return value as optional (try?) or required (try).

func loadFile(named name: String) throws -> File {
    guard let url = urlForFile(named: name) else {
        throw File.Error.missing
    }

    do {
        let data = try Data(contentsOf: url)
        return File(url: url, data: data)
    } catch {
        throw File.Error.invalidData(error)
    }
}

let requiredFile = try loadFile(named: "AppConfig.json")

let optionalFile = try? loadFile(named: "UserSettings.json")

#77 Nested generic types

🐝 Types that are nested in generics automatically inherit their parent's generic types - which is super useful when defining accessory types (for things like states or outcomes).

struct Task<Input, Output> {
    typealias Closure = (Input) throws -> Output

    let closure: Closure
}

extension Task {
    enum Result {
        case success(Output)
        case failure(Error)
    }
}

#76 Equatable & Hashable structures

🤖 Now that the Swift compiler automatically synthesizes Equatable & Hashable conformances for value types, it's easier than ever to setup model structures with nested types that are all Equatable/Hashable!

typealias Value = Hashable & Codable

struct User: Value {
    var name: String
    var age: Int
    var lastLoginDate: Date?
    var settings: Settings
}

extension User {
    struct Settings: Value {
        var itemsPerPage: Int
        var theme: Theme
    }
}

extension User.Settings {
    enum Theme: String, Value {
        case light
        case dark
    }
}

You can read more about using nested types in Swift here.

#75 Conditional conformances

🎉 Swift 4.1 is here! One of the key features it brings is conditional conformances, which lets you have a type only conform to a protocol under certain constraints.

protocol UnboxTransformable {
    associatedtype RawValue

    static func transform(_ value: RawValue) throws -> Self?
}

extension Array: UnboxTransformable where Element: UnboxTransformable {
    typealias RawValue = [Element.RawValue]

    static func transform(_ value: RawValue) throws -> [Element]? {
        return try value.compactMap(Element.transform)
    }
}

I also have an article with lots of more info on conditional conformances here. Paul Hudson also has a great overview of all Swift 4.1 features here.

#74 Generic type aliases

🕵️‍♀️ A cool thing about Swift type aliases is that they can be generic! Combine that with tuples and you can easily define simple generic types.

typealias Pair<T> = (T, T)

extension Game {
    func calculateScore(for players: Pair<Player>) -> Int {
        ...
    }
}

You can read more about using tuples as lightweight types here.

#73 Parsing command line arguments using UserDefaults

☑️ A really cool "hidden" feature of UserDefaults is that it contains any arguments that were passed to the app at launch!

Super useful both in Swift command line tools & scripts, but also to temporarily override a value when debugging iOS apps.

let defaults = UserDefaults.standard
let query = defaults.string(forKey: "query")
let resultCount = defaults.integer(forKey: "results")

#72 Using the & operator

👏 Swift's & operator is awesome! Not only can you use it to compose protocols, you can compose other types too! Very useful if you want to hide concrete types & implementation details.

protocol LoadableFromURL {
    func load(from url: URL)
}

class ContentViewController: UIViewController, LoadableFromURL {
    func load(from url: URL) {
        ...
    }
}

class ViewControllerFactory {
    func makeContentViewController() -> UIViewController & LoadableFromURL {
        return ContentViewController()
    }
}

#71 Capturing multiple values in mocks

🤗 When capturing values in mocks, using an array (instead of just a single value) makes it easy to verify that only a certain number of values were passed.

Perfect for protecting against "over-calling" something.

class UserManagerTests: XCTestCase {
    func testObserversCalledWhenUserFirstLogsIn() {
        let manager = UserManager()

        let observer = ObserverMock()
        manager.addObserver(observer)

        // First login, observers should be notified
        let user = User(id: 123, name: "John")
        manager.userDidLogin(user)
        XCTAssertEqual(observer.users, [user])

        // If the same user logs in again, observers shouldn't be notified
        manager.userDidLogin(user)
        XCTAssertEqual(observer.users, [user])
    }
}

private extension UserManagerTests {
    class ObserverMock: UserManagerObserver {
        private(set) var users = [User]()

        func userDidChange(to user: User) {
            users.append(user)
        }
    }
}

#70 Reducing the need for mocks

👋 When writing tests, you don't always need to create mocks - you can create stubs using real instances of things like errors, URLs & UserDefaults.

Here's how to do that for some common tasks/object types in Swift:

// Create errors using NSError (#function can be used to reference the name of the test)
let error = NSError(domain: #function, code: 1, userInfo: nil)

// Create non-optional URLs using file paths
let url = URL(fileURLWithPath: "Some/URL")

// Reference the test bundle using Bundle(for:)
let bundle = Bundle(for: type(of: self))

// Create an explicit UserDefaults object (instead of having to use a mock)
let userDefaults = UserDefaults(suiteName: #function)

// Create queues to control/await concurrent operations
let queue = DispatchQueue(label: #function)

For when you actually do need mocking, check out "Mocking in Swift".

#69 Using "then" as an external parameter label for closures

⏱ I've started using "then" as an external parameter label for completion handlers. Makes the call site read really nicely (Because I do ❤️ conversational API design) regardless of whether trailing closure syntax is used or not.

protocol DataLoader {
    // Adding type aliases to protocols can be a great way to
    // reduce verbosity for parameter types.
    typealias Handler = (Result<Data>) -> Void
    associatedtype Endpoint

    func loadData(from endpoint: Endpoint, then handler: @escaping Handler)
}

loader.loadData(from: .messages) { result in
    ...
}

loader.loadData(from: .messages, then: { result in
    ...
})

#68 Combining lazily evaluated sequences with the builder pattern

😴 Combining lazily evaluated sequences with builder pattern-like properties can lead to some pretty sweet APIs for configurable sequences in Swift.

Also useful for queries & other things you "build up" and then execute.

// Extension adding builder pattern-like properties that return
// a new sequence value with the given configuration applied
extension FileSequence {
    var recursive: FileSequence {
        var sequence = self
        sequence.isRecursive = true
        return sequence
    }

    var includingHidden: FileSequence {
        var sequence = self
        sequence.includeHidden = true
        return sequence
    }
}

// BEFORE

let files = folder.makeFileSequence(recursive: true, includeHidden: true)

// AFTER

let files = folder.files.recursive.includingHidden

Want an intro to lazy sequences? Check out "Swift sequences: The art of being lazy".

#67 Faster & more stable UI tests

My top 3 tips for faster & more stable UI tests:

📱 Reset the app's state at the beginning of every test.

🆔 Use accessibility identifiers instead of UI strings.

⏱ Use expectations instead of waiting time.

func testOpeningArticle() {
    // Launch the app with an argument that tells it to reset its state
    let app = XCUIApplication()
    app.launchArguments.append("--uitesting")
    app.launch()
    
    // Check that the app is displaying an activity indicator
    let activityIndicator = app.activityIndicator.element
    XCTAssertTrue(activityIndicator.exists)
    
    // Wait for the loading indicator to disappear = content is ready
    expectation(for: NSPredicate(format: "exists == 0"),
                evaluatedWith: activityIndicator)
                
    // Use a generous timeout in case the network is slow
    waitForExpectations(timeout: 10)
    
    // Tap the cell for the first article
    app.tables.cells["Article.0"].tap()
    
    // Assert that a label with the accessibility identifier "Article.Title" exists
    let label = app.staticTexts["Article.Title"]
    XCTAssertTrue(label.exists)
}

#66 Accessing the clipboard from a Swift script

📋 It's super easy to access the contents of the clipboard from a Swift script. A big benefit of Swift scripting is being able to use Cocoa's powerful APIs for Mac apps.

import Cocoa

let clipboard = NSPasteboard.general.string(forType: .string)

#65 Using tuples for view state

🎯 Using Swift tuples for view state can be a super nice way to group multiple properties together and render them reactively using the layout system.

By using a tuple we don't have to either introduce a new type or make our view model-aware.

class TextView: UIView {
    var state: (title: String?, text: String?) {
        // By telling UIKit that our view needs layout and binding our
        // state in layoutSubviews, we can react to state changes without
        // doing unnecessary layout work.
        didSet { setNeedsLayout() }
    }

    private let titleLabel = UILabel()
    private let textLabel = UILabel()

    override func layoutSubviews() {
        super.layoutSubviews()

        titleLabel.text = state.title
        textLabel.text = state.text

        ...
    }
}

#64 Throwing tests and LocalizedError

⚾️ Swift tests can throw, which is super useful in order to avoid complicated logic or force unwrapping. By making errors conform to LocalizedError, you can also get a nice error message in Xcode if there's a failure.

class ImageCacheTests: XCTestCase {
    func testCachingAndLoadingImage() throws {
        let bundle = Bundle(for: type(of: self))
        let cache = ImageCache(bundle: bundle)
        
        // Bonus tip: You can easily load images from your test
        // bundle using this UIImage initializer
        let image = try require(UIImage(named: "sample", in: bundle, compatibleWith: nil))
        try cache.cache(image, forKey: "key")
        
        let cachedImage = try cache.image(forKey: "key")
        XCTAssertEqual(image, cachedImage)
    }
}

enum ImageCacheError {
    case emptyKey
    case dataConversionFailed
}

// When using throwing tests, making your errors conform to
// LocalizedError will render a much nicer error message in
// Xcode (per default only the error code is shown).
extension ImageCacheError: LocalizedError {
    var errorDescription: String? {
        switch self {
        case .emptyKey:
            return "An empty key was given"
        case .dataConversionFailed:
            return "Failed to convert the given image to Data"
        }
    }
}

For more information, and the implementation of the require method used above, check out "Avoiding force unwrapping in Swift unit tests".

#63 The difference between static and class properties

✍️ Unlike static properties, class properties can be overridden by subclasses (however, they can't be stored, only computed).

class TableViewCell: UITableViewCell {
    class var preferredHeight: CGFloat { return 60 }
}

class TallTableViewCell: TableViewCell {
    override class var preferredHeight: CGFloat { return 100 }
}

#62 Creating extensions with static factory methods

👨‍🎨 Creating extensions with static factory methods can be a great alternative to subclassing in Swift, especially for things like setting up UIViews, CALayers or other kinds of styling.

It also lets you remove a lot of styling & setup from your view controllers.

extension UILabel {
    static func makeForTitle() -> UILabel {
        let label = UILabel()
        label.font = .boldSystemFont(ofSize: 24)
        label.textColor = .darkGray
        label.adjustsFontSizeToFitWidth = true
        label.minimumScaleFactor = 0.75
        return label
    }

    static func makeForText() -> UILabel {
        let label = UILabel()
        label.font = .systemFont(ofSize: 16)
        label.textColor = .black
        label.numberOfLines = 0
        return label
    }
}

class ArticleViewController: UIViewController {
    lazy var titleLabel = UILabel.makeForTitle()
    lazy var textLabel = UILabel.makeForText()
}

#61 Child view controller auto-resizing

🧒 An awesome thing about child view controllers is that they're automatically resized to match their parent, making them a super nice solution for things like loading & error views.

class ListViewController: UIViewController {
    func loadItems() {
        let loadingViewController = LoadingViewController()
        add(loadingViewController)

        dataLoader.loadItems { [weak self] result in
            loadingViewController.remove()
            self?.handle(result)
        }
    }
}

For more about child view controller (including the add and remove methods used above), check out "Using child view controllers as plugins in Swift".

#60 Using zip

🤐 Using the zip function in Swift you can easily combine two sequences. Super useful when using two sequences to do some work, since zip takes care of all the bounds-checking.

func render(titles: [String]) {
    for (label, text) in zip(titleLabels, titles) {
        print(text)
        label.text = text
    }
}

#59 Defining custom option sets

🎛 The awesome thing about option sets in Swift is that they can automatically either be passed as a single member or as a set. Even cooler is that you can easily define your own option sets as well, perfect for options and other non-exclusive values.

// Option sets are awesome, because you can easily pass them
// both using dot syntax and array literal syntax, like when
// using the UIView animation API:
UIView.animate(withDuration: 0.3,
               delay: 0,
               options: .allowUserInteraction,
               animations: animations)

UIView.animate(withDuration: 0.3,
               delay: 0,
               options: [.allowUserInteraction, .layoutSubviews],
               animations: animations)

// The cool thing is that you can easily define your own option
// sets as well, by defining a struct that has an Int rawValue,
// that will be used as a bit mask.
extension Cache {
    struct Options: OptionSet {
        static let saveToDisk = Options(rawValue: 1)
        static let clearOnMemoryWarning = Options(rawValue: 1 << 1)
        static let clearDaily = Options(rawValue: 1 << 2)

        let rawValue: Int
    }
}

// We can now use Cache.Options just like UIViewAnimationOptions:
Cache(options: .saveToDisk)
Cache(options: [.saveToDisk, .clearDaily])

#58 Using the where clause with associated types

🙌 Using the where clause when designing protocol-oriented APIs in Swift can let your implementations (or others' if it's open source) have a lot more freedom, especially when it comes to collections.

See "Using generic type constraints in Swift 4" for more info.

public protocol PathFinderMap {
    associatedtype Node
    // Using the 'where' clause for associated types, we can
    // ensure that a type meets certain requirements (in this
    // case that it's a sequence with Node elements).
    associatedtype NodeSequence: Sequence where NodeSequence.Element == Node

    // Instead of using a concrete type (like [Node]) here, we
    // give implementors of this protocol more freedom while
    // still meeting our requirements. For example, one
    // implementation might use Set<Node>.
    func neighbors(of node: Node) -> NodeSequence
}

#57 Using first class functions when iterating over a dictionary

👨‍🍳 Combine first class functions in Swift with the fact that Dictionary elements are (Key, Value) tuples and you can build yourself some pretty awesome functional chains when iterating over a Dictionary.

func makeActor(at coordinate: Coordinate, for building: Building) -> Actor {
    let actor = Actor()
    actor.position = coordinate.point
    actor.animation = building.animation
    return actor
}

func render(_ buildings: [Coordinate : Building]) {
    buildings.map(makeActor).forEach(add)
}

#56 Calling instance methods as static functions

😎 In Swift, you can call any instance method as a static function and it will return a closure representing that method. This is how running tests using SPM on Linux works.

More about this topic in my blog post "First class functions in Swift".

// This produces a '() -> Void' closure which is a reference to the
// given view's 'removeFromSuperview' method.
let closure = UIView.removeFromSuperview(view)

// We can now call it just like we would any other closure, and it
// will run 'view.removeFromSuperview()'
closure()

// This is how running tests using the Swift Package Manager on Linux
// works, you return your test functions as closures:
extension UserManagerTests {
    static var allTests = [
        ("testLoggingIn", testLoggingIn),
        ("testLoggingOut", testLoggingOut),
        ("testUserPermissions", testUserPermissions)
    ]
}

#55 Dropping suffixes from method names to support multiple arguments

👏 One really nice benefit of dropping suffixes from method names (and just using verbs, when possible) is that it becomes super easy to support both single and multiple arguments, and it works really well semantically.

extension UIView {
    func add(_ subviews: UIView...) {
        subviews.forEach(addSubview)
    }
}

view.add(button)
view.add(label)

// By dropping the "Subview" suffix from the method name, both
// single and multiple arguments work really well semantically.
view.add(button, label)

#54 Constraining protocols to classes to ensure mutability

👽 Using the AnyObject (or class) constraint on protocols is not only useful when defining delegates (or other weak references), but also when you always want instances to be mutable without copying.

// By constraining a protocol with 'AnyObject' it can only be adopted
// by classes, which means all instances will always be mutable, and
// that it's the original instance (not a copy) that will be mutated.
protocol DataContainer: AnyObject {
    var data: Data? { get set }
}

class UserSettingsManager {
    private var settings: Settings
    private let dataContainer: DataContainer

    // Since DataContainer is a protocol, we an easily mock it in
    // tests if we use dependency injection
    init(settings: Settings, dataContainer: DataContainer) {
        self.settings = settings
        self.dataContainer = dataContainer
    }

    func saveSettings() throws {
        let data = try settings.serialize()

        // We can now assign properties on an instance of our protocol
        // because the compiler knows it's always going to be a class
        dataContainer.data = data
    }
}

#53 String-based enums in string interpolation

🍣 Even if you define a custom raw value for a string-based enum in Swift, the full case name will be used in string interpolation.

Super useful when using separate raw values for JSON, while still wanting to use the full case name in other contexts.

extension Building {
    // This enum has custom raw values that are used when decoding
    // a value, for example from JSON.
    enum Kind: String {
        case castle = "C"
        case town = "T"
        case barracks = "B"
        case goldMine = "G"
        case camp = "CA"
        case blacksmith = "BL"
    }

    var animation: Animation {
        return Animation(
            // When used in string interpolation, the full case name is still used.
            // For 'castle' this will be 'buildings/castle'.
            name: "buildings/\(kind)",
            frameCount: frameCount,
            frameDuration: frameDuration
        )
    }
}

#52 Expressively comparing a value with a list of candidates

👨‍🔬 Continuing to experiment with expressive ways of comparing a value with a list of candidates in Swift. Adding an extension on Equatable is probably my favorite approach so far.

extension Equatable {
    func isAny(of candidates: Self...) -> Bool {
        return candidates.contains(self)
    }
}

let isHorizontal = direction.isAny(of: .left, .right)

See tip #35 for my previous experiment.

#51 UIView bounds and transforms

📐 A really interesting side-effect of a UIView's bounds being its rect within its own coordinate system is that transforms don't affect it at all. That's why it's usually a better fit than frame when doing layout calculations of subviews.

let view = UIView()
view.frame.size = CGSize(width: 100, height: 100)
view.transform = CGAffineTransform(scaleX: 2, y: 2)

print(view.frame) // (-50.0, -50.0, 200.0, 200.0)
print(view.bounds) // (0.0, 0.0, 100.0, 100.0)

#50 UIKit default arguments

👏 It's awesome that many UIKit APIs with completion handlers and other optional parameters import into Swift with default arguments (even though they are written in Objective-C). Getting rid of all those nil arguments is so nice!

// BEFORE: All parameters are specified, just like in Objective-C

viewController.present(modalViewController, animated: true, completion: nil)

modalViewController.dismiss(animated: true, completion: nil)

viewController.transition(from: loadingViewController,
                          to: contentViewController,
                          duration: 0.3,
                          options: [],
                          animations: animations,
                          completion: nil)

// AFTER: Since many UIKit APIs with completion handlers and other
// optional parameters import into Swift with default arguments,
// we can make our calls shorter

viewController.present(modalViewController, animated: true)

modalViewController.dismiss(animated: true)

viewController.transition(from: loadingViewController,
                          to: contentViewController,
                          duration: 0.3,
                          animations: animations)

#49 Avoiding Massive View Controllers

✂️ Avoiding Massive View Controllers is all about finding the right levels of abstraction and splitting things up.

My personal rule of thumb is that as soon as I have 3 methods or properties that have the same prefix, I break them out into their own type.

// BEFORE

class LoginViewController: UIViewController {
    private lazy var signUpLabel = UILabel()
    private lazy var signUpImageView = UIImageView()
    private lazy var signUpButton = UIButton()
}

// AFTER

class LoginViewController: UIViewController {
    private lazy var signUpView = SignUpView()
}

class SignUpView: UIView {
    private lazy var label = UILabel()
    private lazy var imageView = UIImageView()
    private lazy var button = UIButton()
}

#48 Extending optionals

❤️ I love the fact that optionals are enums in Swift - it makes it so easy to extend them with convenience APIs for certain types. Especially useful when doing things like data validation on optional values.

func validateTextFields() -> Bool {
    guard !usernameTextField.text.isNilOrEmpty else {
        return false
    }

    ...

    return true
}

// Since all optionals are actual enum values in Swift, we can easily
// extend them for certain types, to add our own convenience APIs

extension Optional where Wrapped == String {
    var isNilOrEmpty: Bool {
        switch self {
        case let string?:
            return string.isEmpty
        case nil:
            return true
        }
    }
}

// Since strings are now Collections in Swift 4, you can even
// add this property to all optional collections:

extension Optional where Wrapped: Collection {
    var isNilOrEmpty: Bool {
        switch self {
        case let collection?:
            return collection.isEmpty
        case nil:
            return true
        }
    }
}

#47 Using where with for-loops

🗺 Using the where keyword can be a super nice way to quickly apply a filter in a for-loop in Swift. You can of course use map, filter and forEach, or guard, but for simple loops I think this is very expressive and nice.

func archiveMarkedPosts() {
    for post in posts where post.isMarked {
        archive(post)
    }
}

func healAllies() {
    for player in players where player.isAllied(to: currentPlayer) {
        player.heal()
    }
}

#46 Variable shadowing

👻 Variable shadowing can be super useful in Swift, especially when you want to create a local copy of a parameter value in order to use it as state within a closure.

init(repeatMode: RepeatMode, closure: @escaping () -> UpdateOutcome) {
    // Shadow the argument with a local, mutable copy
    var repeatMode = repeatMode
    
    self.closure = {
        // With shadowing, there's no risk of accidentially
        // referring to the immutable version
        switch repeatMode {
        case .forever:
            break
        case .times(let count):
            guard count > 0 else {
                return .finished
            }
            
            // We can now capture the mutable version and use
            // it for state in a closure
            repeatMode = .times(count - 1)
        }
        
        return closure()
    }
}

#45 Using dot syntax for static properties and initializers

✒️ Dot syntax is one of my favorite features of Swift. What's really cool is that it's not only for enums, any static method or property can be used with dot syntax - even initializers! Perfect for convenience APIs and default parameters.

public enum RepeatMode {
    case times(Int)
    case forever
}

public extension RepeatMode {
    static var never: RepeatMode {
        return .times(0)
    }

    static var once: RepeatMode {
        return .times(1)
    }
}

view.perform(animation, repeated: .once)

// To make default parameters more compact, you can even use init with dot syntax

class ImageLoader {
    init(cache: Cache = .init(), decoder: ImageDecoder = .init()) {
        ...
    }
}

#44 Calling functions as closures with a tuple as parameters

🚀 One really cool aspect of Swift having first class functions is that you can pass any function (or even initializer) as a closure, and even call it with a tuple containing its parameters!

// This function lets us treat any "normal" function or method as
// a closure and run it with a tuple that contains its parameters
func call<Input, Output>(_ function: (Input) -> Output, with input: Input) -> Output {
    return function(input)
}

class ViewFactory {
    func makeHeaderView() -> HeaderView {
        // We can now pass an initializer as a closure, and a tuple
        // containing its parameters
        return call(HeaderView.init, with: loadTextStyles())
    }
    
    private func loadTextStyles() -> (font: UIFont, color: UIColor) {
        return (theme.font, theme.textColor)
    }
}

class HeaderView {
    init(font: UIFont, textColor: UIColor) {
        ...
    }
}

#43 Enabling static dependency injection

💉 If you've been struggling to test code that uses static APIs, here's a technique you can use to enable static dependency injection without having to modify any call sites:

// Before: Almost impossible to test due to the use of singletons

class Analytics {
    static func log(_ event: Event) {
        Database.shared.save(event)
        
        let dictionary = event.serialize()
        NetworkManager.shared.post(dictionary, to: eventURL)
    }
}

// After: Much easier to test, since we can inject mocks as arguments

class Analytics {
    static func log(_ event: Event,
                    database: Database = .shared,
                    networkManager: NetworkManager = .shared) {
        database.save(event)
        
        let dictionary = event.serialize()
        networkManager.post(dictionary, to: eventURL)
    }
}

#42 Type inference for lazy properties in Swift 4

🎉 In Swift 4, type inference works for lazy properties and you don't need to explicitly refer to self!

// Swift 3

class PurchaseView: UIView {
    private lazy var buyButton: UIButton = self.makeBuyButton()
    
    private func makeBuyButton() -> UIButton {
        let button = UIButton()
        button.setTitle("Buy", for: .normal)
        button.setTitleColor(.blue, for: .normal)
        return button
    }
}

// Swift 4

class PurchaseView: UIView {
    private lazy var buyButton = makeBuyButton()
    
    private func makeBuyButton() -> UIButton {
        let button = UIButton()
        button.setTitle("Buy", for: .normal)
        button.setTitleColor(.blue, for: .normal)
        return button
    }
}

#41 Converting Swift errors to NSError

😎 You can turn any Swift Error into an NSError, which is super useful when pattern matching with a code 👍. Also, switching on optionals is pretty cool!

let task = urlSession.dataTask(with: url) { data, _, error in
    switch error {
    case .some(let error as NSError) where error.code == NSURLErrorNotConnectedToInternet:
        presenter.showOfflineView()
    case .some(let error):
        presenter.showGenericErrorView()
    case .none:
        presenter.renderContent(from: data)
    }
}

task.resume()

Also make sure to check out Kostas Kremizas' tip about how you can pattern match directly against a member of URLError.

#40 Making UIImage macOS compatible

🖥 Here's an easy way to make iOS model code that uses UIImage macOS compatible - like me and Gui Rambo discussed on the Swift by Sundell Podcast.

// Either put this in a separate file that you only include in your macOS target or wrap the code in #if os(macOS) / #endif

import Cocoa

// Step 1: Typealias UIImage to NSImage
typealias UIImage = NSImage

// Step 2: You might want to add these APIs that UIImage has but NSImage doesn't.
extension NSImage {
    var cgImage: CGImage? {
        var proposedRect = CGRect(origin: .zero, size: size)

        return cgImage(forProposedRect: &proposedRect,
                       context: nil,
                       hints: nil)
    }

    convenience init?(named name: String) {
        self.init(named: Name(name))
    }
}

// Step 3: Profit - you can now make your model code that uses UIImage cross-platform!
struct User {
    let name: String
    let profileImage: UIImage
}

#39 Internally mutable protocol-oriented APIs

🤖 You can easily define a protocol-oriented API that can only be mutated internally, by using an internal protocol that extends a public one.

// Declare a public protocol that acts as your immutable API
public protocol ModelHolder {
    associatedtype Model
    var model: Model { get }
}

// Declare an extended, internal protocol that provides a mutable API
internal protocol MutableModelHolder: ModelHolder {
    var model: Model { get set }
}

// You can now implement the requirements using 'public internal(set)'
public class UserHolder: MutableModelHolder {
    public internal(set) var model: User

    internal init(model: User) {
        self.model = model
    }
}

#38 Switching on a set

🎛 You can switch on a set using array literals as cases in Swift! Can be really useful to avoid many if/else if statements.

class RoadTile: Tile {
    var connectedDirections = Set<Direction>()

    func render() {
        switch connectedDirections {
        case [.up, .down]:
            image = UIImage(named: "road-vertical")
        case [.left, .right]:
            image = UIImage(named: "road-horizontal")
        default:
            image = UIImage(named: "road")
        }
    }
}

#37 Adding the current locale to cache keys

🌍 When caching localized content in an app, it's a good idea to add the current locale to all keys, to prevent bugs when switching languages.

func cache(_ content: Content, forKey key: String) throws {
    let data = try wrap(content) as Data
    let key = localize(key: key)
    try storage.store(data, forKey: key)
}

func loadCachedContent(forKey key: String) -> Content? {
    let key = localize(key: key)
    let data = storage.loadData(forKey: key)
    return data.flatMap { try? unbox(data: $0) }
}

private func localize(key: String) -> String {
    return key + "-" + Bundle.main.preferredLocalizations[0]
}

#36 Setting up tests to avoid retain cycles with weak references

🚳 Here's an easy way to setup a test to avoid accidental retain cycles with object relationships (like weak delegates & observers) in Swift:

func testDelegateNotRetained() {
    // Assign the delegate (weak) and also retain it using a local var
    var delegate: Delegate? = DelegateMock()
    controller.delegate = delegate
    XCTAssertNotNil(controller.delegate)
    
    // Release the local var, which should also release the weak reference
    delegate = nil
    XCTAssertNil(controller.delegate)
}

#35 Expressively matching a value against a list of candidates

👨‍🔬 Playing around with an expressive way to check if a value matches any of a list of candidates in Swift:

// Instead of multiple conditions like this:

if string == "One" || string == "Two" || string == "Three" {

}

// You can now do:

if string == any(of: "One", "Two", "Three") {

}

You can find a gist with the implementation here.

#34 Organizing code using extensions

👪 APIs in a Swift extension automatically inherit its access control level, making it a neat way to organize public, internal & private APIs.

public extension Animation {
    init(textureNamed textureName: String) {
        frames = [Texture(name: textureName)]
    }
    
    init(texturesNamed textureNames: [String], frameDuration: TimeInterval = 1) {
        frames = textureNames.map(Texture.init)
        self.frameDuration = frameDuration
    }
    
    init(image: Image) {
        frames = [Texture(image: image)]
    }
}

internal extension Animation {
    func loadFrameImages() -> [Image] {
        return frames.map { $0.loadImageIfNeeded() }
    }
}

#33 Using map to transform an optional into a Result type

🗺 Using map you can transform an optional value into an optional Result type by simply passing in the enum case.

enum Result<Value> {
    case value(Value)
    case error(Error)
}

class Promise<Value> {
    private var result: Result<Value>?
    
    init(value: Value? = nil) {
        result = value.map(Result.value)
    }
}

#32 Assigning to self in struct initializers

👌 It's so nice that you can assign directly to self in struct initializers in Swift. Very useful when adding conformance to protocols.

extension Bool: AnswerConvertible {
    public init(input: String) throws {
        switch input.lowercased() {
        case "y", "yes", "👍":
            self = true
        default:
            self = false
        }
    }
}

#31 Recursively calling closures as inline functions

☎️ Defining Swift closures as inline functions enables you to recursively call them, which is super useful in things like custom sequences.

class Database {
    func records(matching query: Query) -> AnySequence<Record> {
        var recordIterator = loadRecords().makeIterator()
        
        func iterate() -> Record? {
            guard let nextRecord = recordIterator.next() else {
                return nil
            }
            
            guard nextRecord.matches(query) else {
                // Since the closure is an inline function, it can be recursively called,
                // in this case in order to advance to the next item.
                return iterate()
            }
            
            return nextRecord
        }
        
        // AnySequence/AnyIterator are part of the standard library and provide an easy way
        // to define custom sequences using closures.
        return AnySequence { AnyIterator(iterate) }
    }
}

Rob Napier points out that using the above might cause crashes if used on a large databaset, since Swift has no guaranteed Tail Call Optimization (TCO).

Slava Pestov also points out that another benefit of inline functions vs closures is that they can have their own generic parameter list.

#30 Passing self to required Objective-C dependencies

🏖 Using lazy properties in Swift, you can pass self to required Objective-C dependencies without having to use force-unwrapped optionals.

class DataLoader: NSObject {
    lazy var urlSession: URLSession = self.makeURLSession()
    
    private func makeURLSession() -> URLSession {
        return URLSession(configuration: .default, delegate: self, delegateQueue: .main)
    }
}

class Renderer {
    lazy var displayLink: CADisplayLink = self.makeDisplayLink()
    
    private func makeDisplayLink() -> CADisplayLink {
        return CADisplayLink(target: self, selector: #selector(screenDidRefresh))
    }
}

#29 Making weak or lazy properties readonly

👓 If you have a property in Swift that needs to be weak or lazy, you can still make it readonly by using private(set).

class Node {
    private(set) weak var parent: Node?
    private(set) lazy var children = [Node]()

    func add(child: Node) {
        children.append(child)
        child.parent = self
    }
}

#28 Defining static URLs using string literals

🌏 Tired of using URL(string: "url")! for static URLs? Make URL conform to ExpressibleByStringLiteral and you can now simply use "url" instead.

extension URL: ExpressibleByStringLiteral {
    // By using 'StaticString' we disable string interpolation, for safety
    public init(stringLiteral value: StaticString) {
        self = URL(string: "\(value)").require(hint: "Invalid URL string literal: \(value)")
    }
}

// We can now define URLs using static string literals 🎉
let url: URL = "https://www.swiftbysundell.com"
let task = URLSession.shared.dataTask(with: "https://www.swiftbysundell.com")

// In Swift 3 or earlier, you also have to implement 2 additional initializers
extension URL {
    public init(extendedGraphemeClusterLiteral value: StaticString) {
        self.init(stringLiteral: value)
    }

    public init(unicodeScalarLiteral value: StaticString) {
        self.init(stringLiteral: value)
    }
}

To find the extension that adds the require() method on Optional that I use above, check out Require.

#27 Manipulating points, sizes and frames using math operators

✚ I'm always careful with operator overloading, but for manipulating things like sizes, points & frames I find them super useful.

extension CGSize {
    static func *(lhs: CGSize, rhs: CGFloat) -> CGSize {
        return CGSize(width: lhs.width * rhs, height: lhs.height * rhs)
    }
}

button.frame.size = image.size * 2

If you like the above idea, check out CGOperators, which contains math operator overloads for all Core Graphics' vector types.

#26 Using closure types in generic constraints

🔗 You can use closure types in generic constraints in Swift. Enables nice APIs for handling sequences of closures.

extension Sequence where Element == () -> Void {
    func callAll() {
        forEach { $0() }
    }
}

extension Sequence where Element == () -> String {
    func joinedResults(separator: String) -> String {
        return map { $0() }.joined(separator: separator)
    }
}

callbacks.callAll()
let names = nameProviders.joinedResults(separator: ", ")

(If you're using Swift 3, you have to change Element to Iterator.Element)

#25 Using associated enum values to avoid state-specific optionals

🎉 Using associated enum values is a super nice way to encapsulate mutually exclusive state info (and avoiding state-specific optionals).

// BEFORE: Lots of state-specific, optional properties

class Player {
    var isWaitingForMatchMaking: Bool
    var invitingUser: User?
    var numberOfLives: Int
    var playerDefeatedBy: Player?
    var roundDefeatedIn: Int?
}

// AFTER: All state-specific information is encapsulated in enum cases

class Player {
    enum State {
        case waitingForMatchMaking
        case waitingForInviteResponse(from: User)
        case active(numberOfLives: Int)
        case defeated(by: Player, roundNumber: Int)
    }
    
    var state: State
}

#24 Using enums for async result types

👍 I really like using enums for all async result types, even boolean ones. Self-documenting, and makes the call site a lot nicer to read too!

protocol PushNotificationService {
    // Before
    func enablePushNotifications(completionHandler: @escaping (Bool) -> Void)
    
    // After
    func enablePushNotifications(completionHandler: @escaping (PushNotificationStatus) -> Void)
}

enum PushNotificationStatus {
    case enabled
    case disabled
}

service.enablePushNotifications { status in
    if status == .enabled {
        enableNotificationsButton.removeFromSuperview()
    }
}

#23 Working on async code in a playground

🏃 Want to work on your async code in a Swift Playground? Just set needsIndefiniteExecution to true to keep it running:

import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
    let greeting = "Hello after 3 seconds"
    print(greeting)
}

To stop the playground from executing, simply call PlaygroundPage.current.finishExecution().

#22 Overriding self with a weak reference

💦 Avoid memory leaks when accidentially refering to self in closures by overriding it locally with a weak reference:

Swift >= 4.2

dataLoader.loadData(from: url) { [weak self] result in
    guard let self = self else { 
        return 
    }

    self.cache(result)
    
    ...

Swift < 4.2

dataLoader.loadData(from: url) { [weak self] result in
    guard let `self` = self else {
        return
    }

    self.cache(result)
    
    ...

Note that the reason the above currently works is because of a compiler bug (which I hope gets turned into a properly supported feature soon).

#21 Using DispatchWorkItem

🕓 Using dispatch work items you can easily cancel a delayed asynchronous GCD task if you no longer need it:

let workItem = DispatchWorkItem {
    // Your async code goes in here
}

// Execute the work item after 1 second
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: workItem)

// You can cancel the work item if you no longer need it
workItem.cancel()

#20 Combining a sequence of functions

➕ While working on a new Swift developer tool (to be open sourced soon 😉), I came up with a pretty neat way of organizing its sequence of operations, by combining their functions into a closure:

internal func +<A, B, C>(lhs: @escaping (A) throws -> B,
                         rhs: @escaping (B) throws -> C) -> (A) throws -> C {
    return { try rhs(lhs($0)) }
}

public func run() throws {
    try (determineTarget + build + analyze + output)()
}

If you're familiar with the functional programming world, you might know the above technique as the pipe operator (thanks to Alexey Demedreckiy for pointing this out!)

#19 Chaining optionals with map() and flatMap()

🗺 Using map() and flatMap() on optionals you can chain multiple operations without having to use lengthy if lets or guards:

// BEFORE

guard let string = argument(at: 1) else {
    return
}

guard let url = URL(string: string) else {
    return
}

handle(url)

// AFTER

argument(at: 1).flatMap(URL.init).map(handle)

#18 Using self-executing closures for lazy properties

🚀 Using self-executing closures is a great way to encapsulate lazy property initialization:

class StoreViewController: UIViewController {
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let view = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
        view.delegate = self
        view.dataSource = self
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(collectionView)
    }
}

#17 Speeding up Swift package tests

⚡️ You can speed up your Swift package tests using the --parallel flag. For Marathon, the tests execute 3 times faster that way!

swift test --parallel

#16 Avoiding mocking UserDefaults

🛠 Struggling with mocking UserDefaults in a test? The good news is: you don't need mocking - just create a real instance:

class LoginTests: XCTestCase {
    private var userDefaults: UserDefaults!
    private var manager: LoginManager!
    
    override func setUp() {
        super.setup()
        
        userDefaults = UserDefaults(suiteName: #file)
        userDefaults.removePersistentDomain(forName: #file)
        
        manager = LoginManager(userDefaults: userDefaults)
    }
}

#15 Using variadic parameters

👍 Using variadic parameters in Swift, you can create some really nice APIs that take a list of objects without having to use an array:

extension Canvas {
    func add(_ shapes: Shape...) {
        shapes.forEach(add)
    }
}

let circle = Circle(center: CGPoint(x: 5, y: 5), radius: 5)
let lineA = Line(start: .zero, end: CGPoint(x: 10, y: 10))
let lineB = Line(start: CGPoint(x: 0, y: 10), end: CGPoint(x: 10, y: 0))

let canvas = Canvas()
canvas.add(circle, lineA, lineB)
canvas.render()

#14 Referring to enum cases with associated values as closures

😮 Just like you can refer to a Swift function as a closure, you can do the same thing with enum cases with associated values:

enum UnboxPath {
    case key(String)
    case keyPath(String)
}

struct UserSchema {
    static let name = key("name")
    static let age = key("age")
    static let posts = key("posts")
    
    private static let key = UnboxPath.key
}

#13 Using the === operator to compare objects by instance

📈 The === operator lets you check if two objects are the same instance. Very useful when verifying that an array contains an instance in a test:

protocol InstanceEquatable: class, Equatable {}

extension InstanceEquatable {
    static func ==(lhs: Self, rhs: Self) -> Bool {
        return lhs === rhs
    }
}

extension Enemy: InstanceEquatable {}

func testDestroyingEnemy() {
    player.attack(enemy)
    XCTAssertTrue(player.destroyedEnemies.contains(enemy))
}

#12 Calling initializers with dot syntax and passing them as closures

😎 Cool thing about Swift initializers: you can call them using dot syntax and pass them as closures! Perfect for mocking dates in tests.

class Logger {
    private let storage: LogStorage
    private let dateProvider: () -> Date
    
    init(storage: LogStorage = .init(), dateProvider: @escaping () -> Date = Date.init) {
        self.storage = storage
        self.dateProvider = dateProvider
    }
    
    func log(event: Event) {
        storage.store(event: event, date: dateProvider())
    }
}

#11 Structuring UI tests as extensions on XCUIApplication

📱 Most of my UI testing logic is now categories on XCUIApplication. Makes the test cases really easy to read:

func testLoggingInAndOut() {
    XCTAssertFalse(app.userIsLoggedIn)
    
    app.launch()
    app.login()
    XCTAssertTrue(app.userIsLoggedIn)
    
    app.logout()
    XCTAssertFalse(app.userIsLoggedIn)
}

func testDisplayingCategories() {
    XCTAssertFalse(app.isDisplayingCategories)
    
    app.launch()
    app.login()
    app.goToCategories()
    XCTAssertTrue(app.isDisplayingCategories)
}

#10 Avoiding default cases in switch statements

🙂 It’s a good idea to avoid “default” cases when switching on Swift enums - it’ll “force you” to update your logic when a new case is added:

enum State {
    case loggedIn
    case loggedOut
    case onboarding
}

func handle(_ state: State) {
    switch state {
    case .loggedIn:
        showMainUI()
    case .loggedOut:
        showLoginUI()
    // Compiler error: Switch must be exhaustive
    }
}

#9 Using the guard statement in many different scopes

💂 It's really cool that you can use Swift's 'guard' statement to exit out of pretty much any scope, not only return from functions:

// You can use the 'guard' statement to...

for string in strings {
    // ...continue an iteration
    guard shouldProcess(string) else {
        continue
    }
    
    // ...or break it
    guard !shouldBreak(for: string) else {
        break
    }
    
    // ...or return
    guard !shouldReturn(for: string) else {
        return
    }
    
    // ..or throw an error
    guard string.isValid else {
        throw StringError.invalid(string)
    }
    
    // ...or exit the program
    guard !shouldExit(for: string) else {
        exit(1)
    }
}

#8 Passing functions & operators as closures

❤️ Love how you can pass functions & operators as closures in Swift. For example, it makes the syntax for sorting arrays really nice!

let array = [3, 9, 1, 4, 6, 2]
let sorted = array.sorted(by: <)

#7 Using #function for UserDefaults key consistency

🗝 Here's a neat little trick I use to get UserDefault key consistency in Swift (#function expands to the property name in getters/setters). Just remember to write a good suite of tests that'll guard you against bugs when changing property names.

extension UserDefaults {
    var onboardingCompleted: Bool {
        get { return bool(forKey: #function) }
        set { set(newValue, forKey: #function) }
    }
}

#6 Using a name already taken by the standard library

📛 Want to use a name already taken by the standard library for a nested type? No problem - just use Swift. to disambiguate:

extension Command {
    enum Error: Swift.Error {
        case missing
        case invalid(String)
    }
}

#5 Using Wrap to implement Equatable

📦 Playing around with using Wrap to implement Equatable for any type, primarily for testing:

protocol AutoEquatable: Equatable {}

extension AutoEquatable {
    static func ==(lhs: Self, rhs: Self) -> Bool {
        let lhsData = try! wrap(lhs) as Data
        let rhsData = try! wrap(rhs) as Data
        return lhsData == rhsData
    }
}

#4 Using typealiases to reduce the length of method signatures

📏 One thing that I find really useful in Swift is to use typealiases to reduce the length of method signatures in generic types:

public class PathFinder<Object: PathFinderObject> {
    public typealias Map = Object.Map
    public typealias Node = Map.Node
    public typealias Path = PathFinderPath<Object>
    
    public static func possiblePaths(for object: Object, at rootNode: Node, on map: Map) -> Path.Sequence {
        return .init(object: object, rootNode: rootNode, map: map)
    }
}

#3 Referencing either external or internal parameter name when writing docs

📖 You can reference either the external or internal parameter label when writing Swift docs - and they get parsed the same:

// EITHER:

class Foo {
    /**
    *   - parameter string: A string
    */
    func bar(with string: String) {}
}

// OR:

class Foo {
    /**
    *   - parameter with: A string
    */
    func bar(with string: String) {}
}

#2 Using auto closures

👍 Finding more and more uses for auto closures in Swift. Can enable some pretty nice APIs:

extension Dictionary {
    mutating func value(for key: Key, orAdd valueClosure: @autoclosure () -> Value) -> Value {
        if let value = self[key] {
            return value
        }
        
        let value = valueClosure()
        self[key] = value
        return value
    }
}

#1 Namespacing with nested types

🚀 I’ve started to become a really big fan of nested types in Swift. Love the additional namespacing it gives you!

public struct Map {
    public struct Model {
        public let size: Size
        public let theme: Theme
        public var terrain: [Position : Terrain.Model]
        public var units: [Position : Unit.Model]
        public var buildings: [Position : Building.Model]
    }
    
    public enum Direction {
        case up
        case right
        case down
        case left
    }
    
    public struct Position {
        public var x: Int
        public var y: Int
    }
    
    public enum Size: String {
        case small = "S"
        case medium = "M"
        case large = "L"
        case extraLarge = "XL"
    }
}

Download Details:

Author: JohnSundell
Source code: https://github.com/JohnSundell/SwiftTips

License: MIT license
#swift 

Rupert  Beatty

Rupert Beatty

1666245660

A Collection Of Swift Tips & Tricks That I've Shared on Twitter

Swift tips & tricks ⚡️

One of the things I really love about Swift is how I keep finding interesting ways to use it in various situations, and when I do - I usually share them on Twitter. Here's a collection of all the tips & tricks that I've shared so far. Each entry has a link to the original tweet, if you want to respond with some feedback or question, which is always super welcome! 🚀

⚠️ This list is no longer being updated. For my latest Swift tips, checkout the "Tips" section on Swift by Sundell.

Also make sure to check out all of my other Swift content:

102 Making async tests faster and more stable

🚀 Here are some quick tips to make async tests faster & more stable:

  • 😴 Avoid sleep() - use expectations instead
  • ⏱ Use generous timeouts to avoid flakiness on CI
  • 🧐 Put all assertions at the end of each test, not inside closures
// BEFORE:

class MentionDetectorTests: XCTestCase {
    func testDetectingMention() {
        let detector = MentionDetector()
        let string = "This test was written by @johnsundell."

        detector.detectMentions(in: string) { mentions in
            XCTAssertEqual(mentions, ["johnsundell"])
        }
        
        sleep(2)
    }
}

// AFTER:

class MentionDetectorTests: XCTestCase {
    func testDetectingMention() {
        let detector = MentionDetector()
        let string = "This test was written by @johnsundell."

        var mentions: [String]?
        let expectation = self.expectation(description: #function)

        detector.detectMentions(in: string) {
            mentions = $0
            expectation.fulfill()
        }

        waitForExpectations(timeout: 10)
        XCTAssertEqual(mentions, ["johnsundell"])
    }
}

For more on async testing, check out "Unit testing asynchronous Swift code".

101 Adding support for Apple Pencil double-taps

✍️ Adding support for the new Apple Pencil double-tap feature is super easy! All you have to do is to create a UIPencilInteraction, add it to a view, and implement one delegate method. Hopefully all pencil-compatible apps will soon adopt this.

let interaction = UIPencilInteraction()
interaction.delegate = self
view.addInteraction(interaction)

extension ViewController: UIPencilInteractionDelegate {
    func pencilInteractionDidTap(_ interaction: UIPencilInteraction) {
        // Handle pencil double-tap
    }
}

For more on using this and other iPad Pro features, check out "Building iPad Pro features in Swift".

100 Combining values with functions

😎 Here's a cool function that combines a value with a function to return a closure that captures that value, so that it can be called without any arguments. Super useful when working with closure-based APIs and we want to use some of our properties without having to capture self.

func combine<A, B>(_ value: A, with closure: @escaping (A) -> B) -> () -> B {
    return { closure(value) }
}

// BEFORE:

class ProductViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        buyButton.handler = { [weak self] in
            guard let self = self else {
                return
            }
            
            self.productManager.startCheckout(for: self.product)
        }
    }
}

// AFTER:

class ProductViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()

        buyButton.handler = combine(product, with: productManager.startCheckout)
    }
}

99 Dependency injection using functions

💉 When I'm only using a single function from a dependency, I love to inject that function as a closure, instead of having to create a protocol and inject the whole object. Makes dependency injection & testing super simple.

final class ArticleLoader {
    typealias Networking = (Endpoint) -> Future<Data>
    
    private let networking: Networking
    
    init(networking: @escaping Networking = URLSession.shared.load) {
        self.networking = networking
    }
    
    func loadLatest() -> Future<[Article]> {
        return networking(.latestArticles).decode()
    }
}

For more on this technique, check out "Simple Swift dependency injection with functions".

98 Using a custom exception handler

💥 It's cool that you can easily assign a closure as a custom NSException handler. This is super useful when building things in Playgrounds - since you can't use breakpoints - so instead of just signal SIGABRT, you'll get the full exception description if something goes wrong.

NSSetUncaughtExceptionHandler { exception in
    print(exception)
}

97 Using type aliases to give semantic meaning to primitives

❤️ I love that in Swift, we can use the type system to make our code so much more self-documenting - one way of doing so is to use type aliases to give the primitive types that we use a more semantic meaning.

extension List.Item {
    // Using type aliases, we can give semantic meaning to the
    // primitive types that we use, without having to introduce
    // wrapper types.
    typealias Index = Int
}

extension List {
    enum Mutation {
        // Our enum cases now become a lot more self-documenting,
        // without having to add additional parameter labels to
        // explain them.
        case add(Item, Item.Index)
        case update(Item, Item.Index)
        case remove(Item.Index)
    }
}

For more on self-documenting code, check out "Writing self-documenting Swift code".

96 Specializing protocols using constraints

🤯 A little late night prototyping session reveals that protocol constraints can not only be applied to extensions - they can also be added to protocol definitions!

This is awesome, since it lets us easily define specialized protocols based on more generic ones.

protocol Component {
    associatedtype Container
    func add(to container: Container)
}

// Protocols that inherit from other protocols can include
// constraints to further specialize them.
protocol ViewComponent: Component where Container == UIView {
    associatedtype View: UIView
    var view: View { get }
}

extension ViewComponent {
    func add(to container: UIView) {
        container.addSubview(view)
    }
}

For more on specializing protocols, check out "Specializing protocols in Swift".

95 Unwrapping an optional or throwing an error

📦 Here's a super handy extension on Swift's Optional type, which gives us a really nice API for easily unwrapping an optional, or throwing an error in case the value turned out to be nil:

extension Optional {
    func orThrow(_ errorExpression: @autoclosure () -> Error) throws -> Wrapped {
        switch self {
        case .some(let value):
            return value
        case .none:
            throw errorExpression()
        }
    }
}

let file = try loadFile(at: path).orThrow(MissingFileError())

For more ways that optionals can be extended, check out "Extending optionals in Swift".

94 Testing code that uses static APIs

👩‍🔬 Testing code that uses static APIs can be really tricky, but there's a way that it can often be done - using Swift's first class function capabilities!

Instead of accessing that static API directly, we can inject the function we want to use, which enables us to mock it!

// BEFORE

class FriendsLoader {
    func loadFriends(then handler: @escaping (Result<[Friend]>) -> Void) {
        Networking.loadData(from: .friends) { result in
            ...
        }
    }
}

// AFTER

class FriendsLoader {
    typealias Handler<T> = (Result<T>) -> Void
    typealias DataLoadingFunction = (Endpoint, @escaping Handler<Data>) -> Void

    func loadFriends(using dataLoading: DataLoadingFunction = Networking.loadData,
                     then handler: @escaping Handler<[Friend]>) {
        dataLoading(.friends) { result in
            ...
        }
    }
}

// MOCKING IN TESTS

let dataLoading: FriendsLoader.DataLoadingFunction = { _, handler in
    handler(.success(mockData))
}

friendsLoader.loadFriends(using: dataLoading) { result in
    ...
}

93 Matching multiple enum cases with associated values

🐾 Swift's pattern matching capabilities are so powerful! Two enum cases with associated values can even be matched and handled by the same switch case - which is super useful when handling state changes with similar data.

enum DownloadState {
    case inProgress(progress: Double)
    case paused(progress: Double)
    case cancelled
    case finished(Data)
}

func downloadStateDidChange(to state: DownloadState) {
    switch state {
    case .inProgress(let progress), .paused(let progress):
        updateProgressView(with: progress)
    case .cancelled:
        showCancelledMessage()
    case .finished(let data):
        process(data)
    }
}

92 Multiline string literals

🅰 One really nice benefit of Swift multiline string literals - even for single lines of text - is that they don't require quotes to be escaped. Perfect when working with things like HTML, or creating a custom description for an object.

let html = highlighter.highlight("Array<String>")

XCTAssertEqual(html, """
<span class="type">Array</span>&lt;<span class="type">String</span>&gt;
""")

91 Reducing sequences

💎 While it's very common in functional programming, the reduce function might be a bit of a hidden gem in Swift. It provides a super useful way to transform a sequence into a single value.

extension Sequence where Element: Equatable {
    func numberOfOccurrences(of target: Element) -> Int {
        return reduce(0) { result, element in
            guard element == target else {
                return result
            }

            return result + 1
        }
    }
}

You can read more about transforming collections in "Transforming collections in Swift".

90 Avoiding manual Codable implementations

📦 When I use Codable in Swift, I want to avoid manual implementations as much as possible, even when there's a mismatch between my code structure and the JSON I'm decoding.

One way that can often be achieved is to use private data containers combined with computed properties.

struct User: Codable {
    let name: String
    let age: Int

    var homeTown: String { return originPlace.name }

    private let originPlace: Place
}

private extension User {
    struct Place: Codable {
        let name: String
    }
}

extension User {
    struct Container: Codable {
        let user: User
    }
}

89 Using feature flags instead of feature branches

🚢 Instead of using feature branches, I merge almost all of my code directly into master - and then I use feature flags to conditionally enable features when they're ready. That way I can avoid merge conflicts and keep shipping!

extension ListViewController {
    func addSearchIfNeeded() {
        // Rather than having to keep maintaining a separate
        // feature branch for a new feature, we can use a flag
        // to conditionally turn it on.
        guard FeatureFlags.searchEnabled else {
            return
        }

        let resultsVC = SearchResultsViewController()
        let searchVC = UISearchController(
            searchResultsController: resultsVC
        )

        searchVC.searchResultsUpdater = resultsVC
        navigationItem.searchController = searchVC
    }
}

You can read more about feature flags in "Feature flags in Swift".

88 Lightweight data hierarchies using tuples

💾 Here I'm using tuples to create a lightweight hierarchy for my data, giving me a nice structure without having to introduce any additional types.

struct CodeSegment {
    var tokens: (
        previous: String?,
        current: String
    )

    var delimiters: (
        previous: Character?
        next: Character?
    )
}

handle(segment.tokens.current)

You can read more about tuples in "Using tuples as lightweight types in Swift"

87 The rule of threes

3️⃣ Whenever I have 3 properties or local variables that share the same prefix, I usually try to extract them into their own method or type. That way I can avoid massive types & methods, and also increase readability, without falling into a "premature optimization" trap.

Before

public func generate() throws {
    let contentFolder = try folder.subfolder(named: "content")

    let articleFolder = try contentFolder.subfolder(named: "posts")
    let articleProcessor = ContentProcessor(folder: articleFolder)
    let articles = try articleProcessor.process()

    ...
}

After

public func generate() throws {
    let contentFolder = try folder.subfolder(named: "content")
    let articles = try processArticles(in: contentFolder)
    ...
}

private func processArticles(in folder: Folder) throws -> [ContentItem] {
    let folder = try folder.subfolder(named: "posts")
    let processor = ContentProcessor(folder: folder)
    return try processor.process()
}

86 Useful Codable extensions

👨‍🔧 Here's two extensions that I always add to the Encodable & Decodable protocols, which for me really make the Codable API nicer to use. By using type inference for decoding, a lot of boilerplate can be removed when the compiler is already able to infer the resulting type.

extension Encodable {
    func encoded() throws -> Data {
        return try JSONEncoder().encode(self)
    }
}

extension Data {
    func decoded<T: Decodable>() throws -> T {
        return try JSONDecoder().decode(T.self, from: self)
    }
}

let data = try user.encoded()

// By using a generic type in the decoded() method, the
// compiler can often infer the type we want to decode
// from the current context.
try userDidLogin(data.decoded())

// And if not, we can always supply the type, still making
// the call site read very nicely.
let otherUser = try data.decoded() as User

85 Using shared UserDefaults suites

📦 UserDefaults is a lot more powerful than what it first might seem like. Not only can it store more complex values (like dates & dictionaries) and parse command line arguments - it also enables easy sharing of settings & lightweight data between apps in the same App Group.

let sharedDefaults = UserDefaults(suiteName: "my-app-group")!
let useDarkMode = sharedDefaults.bool(forKey: "dark-mode")

// This value is put into the shared suite.
sharedDefaults.set(true, forKey: "dark-mode")

// If you want to treat the shared settings as read-only (and add
// local overrides on top of them), you can simply add the shared
// suite to the standard UserDefaults.
let combinedDefaults = UserDefaults.standard
combinedDefaults.addSuite(named: "my-app-group")

// This value is a local override, not added to the shared suite.
combinedDefaults.set(true, forKey: "app-specific-override")

84 Custom UIView backing layers

🎨 By overriding layerClass you can tell UIKit what CALayer class to use for a UIView's backing layer. That way you can reduce the amount of layers, and don't have to do any manual layout.

final class GradientView: UIView {
    override class var layerClass: AnyClass { return CAGradientLayer.self }

    var colors: (start: UIColor, end: UIColor)? {
        didSet { updateLayer() }
    }

    private func updateLayer() {
        let layer = self.layer as! CAGradientLayer
        layer.colors = colors.map { [$0.start.cgColor, $0.end.cgColor] }
    }
}

83 Auto-Equatable enums with associated values

✅ That the compiler now automatically synthesizes Equatable conformances is such a huge upgrade for Swift! And the cool thing is that it works for all kinds of types - even for enums with associated values! Especially useful when using enums for verification in unit tests.

struct Article: Equatable {
    let title: String
    let text: String
}

struct User: Equatable {
    let name: String
    let age: Int
}

extension Navigator {
    enum Destination: Equatable {
        case profile(User)
        case article(Article)
    }
}

func testNavigatingToArticle() {
    let article = Article(title: "Title", text: "Text")
    controller.select(article)
    XCTAssertEqual(navigator.destinations, [.article(article)])
}

82 Defaults for associated types

🤝 Associated types can have defaults in Swift - which is super useful for types that are not easily inferred (for example when they're not used for a specific instance method or property).

protocol Identifiable {
    associatedtype RawIdentifier: Codable = String

    var id: Identifier<Self> { get }
}

struct User: Identifiable {
    let id: Identifier<User>
    let name: String
}

struct Group: Identifiable {
    typealias RawIdentifier = Int

    let id: Identifier<Group>
    let name: String
}

81 Creating a dedicated identifier type

🆔 If you want to avoid using plain strings as identifiers (which can increase both type safety & readability), it's really easy to create a custom Identifier type that feels just like a native Swift type, thanks to protocols!

More on this topic in "Type-safe identifiers in Swift".

struct Identifier: Hashable {
    let string: String
}

extension Identifier: ExpressibleByStringLiteral {
    init(stringLiteral value: String) {
        string = value
    }
}

extension Identifier: CustomStringConvertible {
    var description: String {
        return string
    }
}

extension Identifier: Codable {
    init(from decoder: Decoder) throws {
        let container = try decoder.singleValueContainer()
        string = try container.decode(String.self)
    }

    func encode(to encoder: Encoder) throws {
        var container = encoder.singleValueContainer()
        try container.encode(string)
    }
}

struct Article: Codable {
    let id: Identifier
    let title: String
}

let article = Article(id: "my-article", title: "Hello world!")

80 Assigning optional tuple members to variables

🙌 A really cool thing about using tuples to model the internal state of a Swift type, is that you can unwrap an optional tuple's members directly into local variables.

Very useful in order to group multiple optional values together for easy unwrapping & handling.

class ImageTransformer {
    private var queue = [(image: UIImage, transform: Transform)]()

    private func processNext() {
        // When unwrapping an optional tuple, you can assign the members
        // directly to local variables.
        guard let (image, transform) = queue.first else {
            return
        }

        let context = Context()
        context.draw(image)
        context.apply(transform)
        ...
    }
}

79 Struct convenience initializers

❤️ I love to structure my code using extensions in Swift. One big benefit of doing so when it comes to struct initializers, is that defining a convenience initializer doesn't remove the default one the compiler generates - best of both worlds!

struct Article {
    let date: Date
    var title: String
    var text: String
    var comments: [Comment]
}

extension Article {
    init(title: String, text: String) {
        self.init(date: Date(), title: title, text: text, comments: [])
    }
}

let articleA = Article(title: "Best Cupcake Recipe", text: "...")

let articleB = Article(
    date: Date(),
    title: "Best Cupcake Recipe",
    text: "...",
    comments: [
        Comment(user: currentUser, text: "Yep, can confirm!")
    ]
)

78 Usages of throwing functions

🏈 A big benefit of using throwing functions for synchronous Swift APIs is that the caller can decide whether they want to treat the return value as optional (try?) or required (try).

func loadFile(named name: String) throws -> File {
    guard let url = urlForFile(named: name) else {
        throw File.Error.missing
    }

    do {
        let data = try Data(contentsOf: url)
        return File(url: url, data: data)
    } catch {
        throw File.Error.invalidData(error)
    }
}

let requiredFile = try loadFile(named: "AppConfig.json")

let optionalFile = try? loadFile(named: "UserSettings.json")

77 Nested generic types

🐝 Types that are nested in generics automatically inherit their parent's generic types - which is super useful when defining accessory types (for things like states or outcomes).

struct Task<Input, Output> {
    typealias Closure = (Input) throws -> Output

    let closure: Closure
}

extension Task {
    enum Result {
        case success(Output)
        case failure(Error)
    }
}

76 Equatable & Hashable structures

🤖 Now that the Swift compiler automatically synthesizes Equatable & Hashable conformances for value types, it's easier than ever to setup model structures with nested types that are all Equatable/Hashable!

typealias Value = Hashable & Codable

struct User: Value {
    var name: String
    var age: Int
    var lastLoginDate: Date?
    var settings: Settings
}

extension User {
    struct Settings: Value {
        var itemsPerPage: Int
        var theme: Theme
    }
}

extension User.Settings {
    enum Theme: String, Value {
        case light
        case dark
    }
}

You can read more about using nested types in Swift here.

75 Conditional conformances

🎉 Swift 4.1 is here! One of the key features it brings is conditional conformances, which lets you have a type only conform to a protocol under certain constraints.

protocol UnboxTransformable {
    associatedtype RawValue

    static func transform(_ value: RawValue) throws -> Self?
}

extension Array: UnboxTransformable where Element: UnboxTransformable {
    typealias RawValue = [Element.RawValue]

    static func transform(_ value: RawValue) throws -> [Element]? {
        return try value.compactMap(Element.transform)
    }
}

I also have an article with lots of more info on conditional conformances here. Paul Hudson also has a great overview of all Swift 4.1 features here.

74 Generic type aliases

🕵️‍♀️ A cool thing about Swift type aliases is that they can be generic! Combine that with tuples and you can easily define simple generic types.

typealias Pair<T> = (T, T)

extension Game {
    func calculateScore(for players: Pair<Player>) -> Int {
        ...
    }
}

You can read more about using tuples as lightweight types here.

73 Parsing command line arguments using UserDefaults

☑️ A really cool "hidden" feature of UserDefaults is that it contains any arguments that were passed to the app at launch!

Super useful both in Swift command line tools & scripts, but also to temporarily override a value when debugging iOS apps.

let defaults = UserDefaults.standard
let query = defaults.string(forKey: "query")
let resultCount = defaults.integer(forKey: "results")

72 Using the & operator

👏 Swift's & operator is awesome! Not only can you use it to compose protocols, you can compose other types too! Very useful if you want to hide concrete types & implementation details.

protocol LoadableFromURL {
    func load(from url: URL)
}

class ContentViewController: UIViewController, LoadableFromURL {
    func load(from url: URL) {
        ...
    }
}

class ViewControllerFactory {
    func makeContentViewController() -> UIViewController & LoadableFromURL {
        return ContentViewController()
    }
}

71 Capturing multiple values in mocks

🤗 When capturing values in mocks, using an array (instead of just a single value) makes it easy to verify that only a certain number of values were passed.

Perfect for protecting against "over-calling" something.

class UserManagerTests: XCTestCase {
    func testObserversCalledWhenUserFirstLogsIn() {
        let manager = UserManager()

        let observer = ObserverMock()
        manager.addObserver(observer)

        // First login, observers should be notified
        let user = User(id: 123, name: "John")
        manager.userDidLogin(user)
        XCTAssertEqual(observer.users, [user])

        // If the same user logs in again, observers shouldn't be notified
        manager.userDidLogin(user)
        XCTAssertEqual(observer.users, [user])
    }
}

private extension UserManagerTests {
    class ObserverMock: UserManagerObserver {
        private(set) var users = [User]()

        func userDidChange(to user: User) {
            users.append(user)
        }
    }
}

70 Reducing the need for mocks

👋 When writing tests, you don't always need to create mocks - you can create stubs using real instances of things like errors, URLs & UserDefaults.

Here's how to do that for some common tasks/object types in Swift:

// Create errors using NSError (#function can be used to reference the name of the test)
let error = NSError(domain: #function, code: 1, userInfo: nil)

// Create non-optional URLs using file paths
let url = URL(fileURLWithPath: "Some/URL")

// Reference the test bundle using Bundle(for:)
let bundle = Bundle(for: type(of: self))

// Create an explicit UserDefaults object (instead of having to use a mock)
let userDefaults = UserDefaults(suiteName: #function)

// Create queues to control/await concurrent operations
let queue = DispatchQueue(label: #function)

For when you actually do need mocking, check out "Mocking in Swift".

69 Using "then" as an external parameter label for closures

⏱ I've started using "then" as an external parameter label for completion handlers. Makes the call site read really nicely (Because I do ❤️ conversational API design) regardless of whether trailing closure syntax is used or not.

protocol DataLoader {
    // Adding type aliases to protocols can be a great way to
    // reduce verbosity for parameter types.
    typealias Handler = (Result<Data>) -> Void
    associatedtype Endpoint

    func loadData(from endpoint: Endpoint, then handler: @escaping Handler)
}

loader.loadData(from: .messages) { result in
    ...
}

loader.loadData(from: .messages, then: { result in
    ...
})

68 Combining lazily evaluated sequences with the builder pattern

😴 Combining lazily evaluated sequences with builder pattern-like properties can lead to some pretty sweet APIs for configurable sequences in Swift.

Also useful for queries & other things you "build up" and then execute.

// Extension adding builder pattern-like properties that return
// a new sequence value with the given configuration applied
extension FileSequence {
    var recursive: FileSequence {
        var sequence = self
        sequence.isRecursive = true
        return sequence
    }

    var includingHidden: FileSequence {
        var sequence = self
        sequence.includeHidden = true
        return sequence
    }
}

// BEFORE

let files = folder.makeFileSequence(recursive: true, includeHidden: true)

// AFTER

let files = folder.files.recursive.includingHidden

Want an intro to lazy sequences? Check out "Swift sequences: The art of being lazy".

67 Faster & more stable UI tests

My top 3 tips for faster & more stable UI tests:

📱 Reset the app's state at the beginning of every test.

🆔 Use accessibility identifiers instead of UI strings.

⏱ Use expectations instead of waiting time.

func testOpeningArticle() {
    // Launch the app with an argument that tells it to reset its state
    let app = XCUIApplication()
    app.launchArguments.append("--uitesting")
    app.launch()
    
    // Check that the app is displaying an activity indicator
    let activityIndicator = app.activityIndicator.element
    XCTAssertTrue(activityIndicator.exists)
    
    // Wait for the loading indicator to disappear = content is ready
    expectation(for: NSPredicate(format: "exists == 0"),
                evaluatedWith: activityIndicator)
                
    // Use a generous timeout in case the network is slow
    waitForExpectations(timeout: 10)
    
    // Tap the cell for the first article
    app.tables.cells["Article.0"].tap()
    
    // Assert that a label with the accessibility identifier "Article.Title" exists
    let label = app.staticTexts["Article.Title"]
    XCTAssertTrue(label.exists)
}

66 Accessing the clipboard from a Swift script

📋 It's super easy to access the contents of the clipboard from a Swift script. A big benefit of Swift scripting is being able to use Cocoa's powerful APIs for Mac apps.

import Cocoa

let clipboard = NSPasteboard.general.string(forType: .string)

65 Using tuples for view state

🎯 Using Swift tuples for view state can be a super nice way to group multiple properties together and render them reactively using the layout system.

By using a tuple we don't have to either introduce a new type or make our view model-aware.

class TextView: UIView {
    var state: (title: String?, text: String?) {
        // By telling UIKit that our view needs layout and binding our
        // state in layoutSubviews, we can react to state changes without
        // doing unnecessary layout work.
        didSet { setNeedsLayout() }
    }

    private let titleLabel = UILabel()
    private let textLabel = UILabel()

    override func layoutSubviews() {
        super.layoutSubviews()

        titleLabel.text = state.title
        textLabel.text = state.text

        ...
    }
}

64 Throwing tests and LocalizedError

⚾️ Swift tests can throw, which is super useful in order to avoid complicated logic or force unwrapping. By making errors conform to LocalizedError, you can also get a nice error message in Xcode if there's a failure.

class ImageCacheTests: XCTestCase {
    func testCachingAndLoadingImage() throws {
        let bundle = Bundle(for: type(of: self))
        let cache = ImageCache(bundle: bundle)
        
        // Bonus tip: You can easily load images from your test
        // bundle using this UIImage initializer
        let image = try require(UIImage(named: "sample", in: bundle, compatibleWith: nil))
        try cache.cache(image, forKey: "key")
        
        let cachedImage = try cache.image(forKey: "key")
        XCTAssertEqual(image, cachedImage)
    }
}

enum ImageCacheError {
    case emptyKey
    case dataConversionFailed
}

// When using throwing tests, making your errors conform to
// LocalizedError will render a much nicer error message in
// Xcode (per default only the error code is shown).
extension ImageCacheError: LocalizedError {
    var errorDescription: String? {
        switch self {
        case .emptyKey:
            return "An empty key was given"
        case .dataConversionFailed:
            return "Failed to convert the given image to Data"
        }
    }
}

For more information, and the implementation of the require method used above, check out "Avoiding force unwrapping in Swift unit tests".

63 The difference between static and class properties

✍️ Unlike static properties, class properties can be overridden by subclasses (however, they can't be stored, only computed).

class TableViewCell: UITableViewCell {
    class var preferredHeight: CGFloat { return 60 }
}

class TallTableViewCell: TableViewCell {
    override class var preferredHeight: CGFloat { return 100 }
}

62 Creating extensions with static factory methods

👨‍🎨 Creating extensions with static factory methods can be a great alternative to subclassing in Swift, especially for things like setting up UIViews, CALayers or other kinds of styling.

It also lets you remove a lot of styling & setup from your view controllers.

extension UILabel {
    static func makeForTitle() -> UILabel {
        let label = UILabel()
        label.font = .boldSystemFont(ofSize: 24)
        label.textColor = .darkGray
        label.adjustsFontSizeToFitWidth = true
        label.minimumScaleFactor = 0.75
        return label
    }

    static func makeForText() -> UILabel {
        let label = UILabel()
        label.font = .systemFont(ofSize: 16)
        label.textColor = .black
        label.numberOfLines = 0
        return label
    }
}

class ArticleViewController: UIViewController {
    lazy var titleLabel = UILabel.makeForTitle()
    lazy var textLabel = UILabel.makeForText()
}

61 Child view controller auto-resizing

🧒 An awesome thing about child view controllers is that they're automatically resized to match their parent, making them a super nice solution for things like loading & error views.

class ListViewController: UIViewController {
    func loadItems() {
        let loadingViewController = LoadingViewController()
        add(loadingViewController)

        dataLoader.loadItems { [weak self] result in
            loadingViewController.remove()
            self?.handle(result)
        }
    }
}

For more about child view controller (including the add and remove methods used above), check out "Using child view controllers as plugins in Swift".

60 Using zip

🤐 Using the zip function in Swift you can easily combine two sequences. Super useful when using two sequences to do some work, since zip takes care of all the bounds-checking.

func render(titles: [String]) {
    for (label, text) in zip(titleLabels, titles) {
        print(text)
        label.text = text
    }
}

59 Defining custom option sets

🎛 The awesome thing about option sets in Swift is that they can automatically either be passed as a single member or as a set. Even cooler is that you can easily define your own option sets as well, perfect for options and other non-exclusive values.

// Option sets are awesome, because you can easily pass them
// both using dot syntax and array literal syntax, like when
// using the UIView animation API:
UIView.animate(withDuration: 0.3,
               delay: 0,
               options: .allowUserInteraction,
               animations: animations)

UIView.animate(withDuration: 0.3,
               delay: 0,
               options: [.allowUserInteraction, .layoutSubviews],
               animations: animations)

// The cool thing is that you can easily define your own option
// sets as well, by defining a struct that has an Int rawValue,
// that will be used as a bit mask.
extension Cache {
    struct Options: OptionSet {
        static let saveToDisk = Options(rawValue: 1)
        static let clearOnMemoryWarning = Options(rawValue: 1 << 1)
        static let clearDaily = Options(rawValue: 1 << 2)

        let rawValue: Int
    }
}

// We can now use Cache.Options just like UIViewAnimationOptions:
Cache(options: .saveToDisk)
Cache(options: [.saveToDisk, .clearDaily])

58 Using the where clause with associated types

🙌 Using the where clause when designing protocol-oriented APIs in Swift can let your implementations (or others' if it's open source) have a lot more freedom, especially when it comes to collections.

See "Using generic type constraints in Swift 4" for more info.

public protocol PathFinderMap {
    associatedtype Node
    // Using the 'where' clause for associated types, we can
    // ensure that a type meets certain requirements (in this
    // case that it's a sequence with Node elements).
    associatedtype NodeSequence: Sequence where NodeSequence.Element == Node

    // Instead of using a concrete type (like [Node]) here, we
    // give implementors of this protocol more freedom while
    // still meeting our requirements. For example, one
    // implementation might use Set<Node>.
    func neighbors(of node: Node) -> NodeSequence
}

57 Using first class functions when iterating over a dictionary

👨‍🍳 Combine first class functions in Swift with the fact that Dictionary elements are (Key, Value) tuples and you can build yourself some pretty awesome functional chains when iterating over a Dictionary.

func makeActor(at coordinate: Coordinate, for building: Building) -> Actor {
    let actor = Actor()
    actor.position = coordinate.point
    actor.animation = building.animation
    return actor
}

func render(_ buildings: [Coordinate : Building]) {
    buildings.map(makeActor).forEach(add)
}

56 Calling instance methods as static functions

😎 In Swift, you can call any instance method as a static function and it will return a closure representing that method. This is how running tests using SPM on Linux works.

More about this topic in my blog post "First class functions in Swift".

// This produces a '() -> Void' closure which is a reference to the
// given view's 'removeFromSuperview' method.
let closure = UIView.removeFromSuperview(view)

// We can now call it just like we would any other closure, and it
// will run 'view.removeFromSuperview()'
closure()

// This is how running tests using the Swift Package Manager on Linux
// works, you return your test functions as closures:
extension UserManagerTests {
    static var allTests = [
        ("testLoggingIn", testLoggingIn),
        ("testLoggingOut", testLoggingOut),
        ("testUserPermissions", testUserPermissions)
    ]
}

55 Dropping suffixes from method names to support multiple arguments

👏 One really nice benefit of dropping suffixes from method names (and just using verbs, when possible) is that it becomes super easy to support both single and multiple arguments, and it works really well semantically.

extension UIView {
    func add(_ subviews: UIView...) {
        subviews.forEach(addSubview)
    }
}

view.add(button)
view.add(label)

// By dropping the "Subview" suffix from the method name, both
// single and multiple arguments work really well semantically.
view.add(button, label)

54 Constraining protocols to classes to ensure mutability

👽 Using the AnyObject (or class) constraint on protocols is not only useful when defining delegates (or other weak references), but also when you always want instances to be mutable without copying.

// By constraining a protocol with 'AnyObject' it can only be adopted
// by classes, which means all instances will always be mutable, and
// that it's the original instance (not a copy) that will be mutated.
protocol DataContainer: AnyObject {
    var data: Data? { get set }
}

class UserSettingsManager {
    private var settings: Settings
    private let dataContainer: DataContainer

    // Since DataContainer is a protocol, we an easily mock it in
    // tests if we use dependency injection
    init(settings: Settings, dataContainer: DataContainer) {
        self.settings = settings
        self.dataContainer = dataContainer
    }

    func saveSettings() throws {
        let data = try settings.serialize()

        // We can now assign properties on an instance of our protocol
        // because the compiler knows it's always going to be a class
        dataContainer.data = data
    }
}

53 String-based enums in string interpolation

🍣 Even if you define a custom raw value for a string-based enum in Swift, the full case name will be used in string interpolation.

Super useful when using separate raw values for JSON, while still wanting to use the full case name in other contexts.

extension Building {
    // This enum has custom raw values that are used when decoding
    // a value, for example from JSON.
    enum Kind: String {
        case castle = "C"
        case town = "T"
        case barracks = "B"
        case goldMine = "G"
        case camp = "CA"
        case blacksmith = "BL"
    }

    var animation: Animation {
        return Animation(
            // When used in string interpolation, the full case name is still used.
            // For 'castle' this will be 'buildings/castle'.
            name: "buildings/\(kind)",
            frameCount: frameCount,
            frameDuration: frameDuration
        )
    }
}

52 Expressively comparing a value with a list of candidates

👨‍🔬 Continuing to experiment with expressive ways of comparing a value with a list of candidates in Swift. Adding an extension on Equatable is probably my favorite approach so far.

extension Equatable {
    func isAny(of candidates: Self...) -> Bool {
        return candidates.contains(self)
    }
}

let isHorizontal = direction.isAny(of: .left, .right)

See tip 35 for my previous experiment.

51 UIView bounds and transforms

📐 A really interesting side-effect of a UIView's bounds being its rect within its own coordinate system is that transforms don't affect it at all. That's why it's usually a better fit than frame when doing layout calculations of subviews.

let view = UIView()
view.frame.size = CGSize(width: 100, height: 100)
view.transform = CGAffineTransform(scaleX: 2, y: 2)

print(view.frame) // (-50.0, -50.0, 200.0, 200.0)
print(view.bounds) // (0.0, 0.0, 100.0, 100.0)

50 UIKit default arguments

👏 It's awesome that many UIKit APIs with completion handlers and other optional parameters import into Swift with default arguments (even though they are written in Objective-C). Getting rid of all those nil arguments is so nice!

// BEFORE: All parameters are specified, just like in Objective-C

viewController.present(modalViewController, animated: true, completion: nil)

modalViewController.dismiss(animated: true, completion: nil)

viewController.transition(from: loadingViewController,
                          to: contentViewController,
                          duration: 0.3,
                          options: [],
                          animations: animations,
                          completion: nil)

// AFTER: Since many UIKit APIs with completion handlers and other
// optional parameters import into Swift with default arguments,
// we can make our calls shorter

viewController.present(modalViewController, animated: true)

modalViewController.dismiss(animated: true)

viewController.transition(from: loadingViewController,
                          to: contentViewController,
                          duration: 0.3,
                          animations: animations)

49 Avoiding Massive View Controllers

✂️ Avoiding Massive View Controllers is all about finding the right levels of abstraction and splitting things up.

My personal rule of thumb is that as soon as I have 3 methods or properties that have the same prefix, I break them out into their own type.

// BEFORE

class LoginViewController: UIViewController {
    private lazy var signUpLabel = UILabel()
    private lazy var signUpImageView = UIImageView()
    private lazy var signUpButton = UIButton()
}

// AFTER

class LoginViewController: UIViewController {
    private lazy var signUpView = SignUpView()
}

class SignUpView: UIView {
    private lazy var label = UILabel()
    private lazy var imageView = UIImageView()
    private lazy var button = UIButton()
}

48 Extending optionals

❤️ I love the fact that optionals are enums in Swift - it makes it so easy to extend them with convenience APIs for certain types. Especially useful when doing things like data validation on optional values.

func validateTextFields() -> Bool {
    guard !usernameTextField.text.isNilOrEmpty else {
        return false
    }

    ...

    return true
}

// Since all optionals are actual enum values in Swift, we can easily
// extend them for certain types, to add our own convenience APIs

extension Optional where Wrapped == String {
    var isNilOrEmpty: Bool {
        switch self {
        case let string?:
            return string.isEmpty
        case nil:
            return true
        }
    }
}

// Since strings are now Collections in Swift 4, you can even
// add this property to all optional collections:

extension Optional where Wrapped: Collection {
    var isNilOrEmpty: Bool {
        switch self {
        case let collection?:
            return collection.isEmpty
        case nil:
            return true
        }
    }
}

47 Using where with for-loops

🗺 Using the where keyword can be a super nice way to quickly apply a filter in a for-loop in Swift. You can of course use map, filter and forEach, or guard, but for simple loops I think this is very expressive and nice.

func archiveMarkedPosts() {
    for post in posts where post.isMarked {
        archive(post)
    }
}

func healAllies() {
    for player in players where player.isAllied(to: currentPlayer) {
        player.heal()
    }
}

46 Variable shadowing

👻 Variable shadowing can be super useful in Swift, especially when you want to create a local copy of a parameter value in order to use it as state within a closure.

init(repeatMode: RepeatMode, closure: @escaping () -> UpdateOutcome) {
    // Shadow the argument with a local, mutable copy
    var repeatMode = repeatMode
    
    self.closure = {
        // With shadowing, there's no risk of accidentially
        // referring to the immutable version
        switch repeatMode {
        case .forever:
            break
        case .times(let count):
            guard count > 0 else {
                return .finished
            }
            
            // We can now capture the mutable version and use
            // it for state in a closure
            repeatMode = .times(count - 1)
        }
        
        return closure()
    }
}

45 Using dot syntax for static properties and initializers

✒️ Dot syntax is one of my favorite features of Swift. What's really cool is that it's not only for enums, any static method or property can be used with dot syntax - even initializers! Perfect for convenience APIs and default parameters.

public enum RepeatMode {
    case times(Int)
    case forever
}

public extension RepeatMode {
    static var never: RepeatMode {
        return .times(0)
    }

    static var once: RepeatMode {
        return .times(1)
    }
}

view.perform(animation, repeated: .once)

// To make default parameters more compact, you can even use init with dot syntax

class ImageLoader {
    init(cache: Cache = .init(), decoder: ImageDecoder = .init()) {
        ...
    }
}

44 Calling functions as closures with a tuple as parameters

🚀 One really cool aspect of Swift having first class functions is that you can pass any function (or even initializer) as a closure, and even call it with a tuple containing its parameters!

// This function lets us treat any "normal" function or method as
// a closure and run it with a tuple that contains its parameters
func call<Input, Output>(_ function: (Input) -> Output, with input: Input) -> Output {
    return function(input)
}

class ViewFactory {
    func makeHeaderView() -> HeaderView {
        // We can now pass an initializer as a closure, and a tuple
        // containing its parameters
        return call(HeaderView.init, with: loadTextStyles())
    }
    
    private func loadTextStyles() -> (font: UIFont, color: UIColor) {
        return (theme.font, theme.textColor)
    }
}

class HeaderView {
    init(font: UIFont, textColor: UIColor) {
        ...
    }
}

43 Enabling static dependency injection

💉 If you've been struggling to test code that uses static APIs, here's a technique you can use to enable static dependency injection without having to modify any call sites:

// Before: Almost impossible to test due to the use of singletons

class Analytics {
    static func log(_ event: Event) {
        Database.shared.save(event)
        
        let dictionary = event.serialize()
        NetworkManager.shared.post(dictionary, to: eventURL)
    }
}

// After: Much easier to test, since we can inject mocks as arguments

class Analytics {
    static func log(_ event: Event,
                    database: Database = .shared,
                    networkManager: NetworkManager = .shared) {
        database.save(event)
        
        let dictionary = event.serialize()
        networkManager.post(dictionary, to: eventURL)
    }
}

42 Type inference for lazy properties in Swift 4

🎉 In Swift 4, type inference works for lazy properties and you don't need to explicitly refer to self!

// Swift 3

class PurchaseView: UIView {
    private lazy var buyButton: UIButton = self.makeBuyButton()
    
    private func makeBuyButton() -> UIButton {
        let button = UIButton()
        button.setTitle("Buy", for: .normal)
        button.setTitleColor(.blue, for: .normal)
        return button
    }
}

// Swift 4

class PurchaseView: UIView {
    private lazy var buyButton = makeBuyButton()
    
    private func makeBuyButton() -> UIButton {
        let button = UIButton()
        button.setTitle("Buy", for: .normal)
        button.setTitleColor(.blue, for: .normal)
        return button
    }
}

41 Converting Swift errors to NSError

😎 You can turn any Swift Error into an NSError, which is super useful when pattern matching with a code 👍. Also, switching on optionals is pretty cool!

let task = urlSession.dataTask(with: url) { data, _, error in
    switch error {
    case .some(let error as NSError) where error.code == NSURLErrorNotConnectedToInternet:
        presenter.showOfflineView()
    case .some(let error):
        presenter.showGenericErrorView()
    case .none:
        presenter.renderContent(from: data)
    }
}

task.resume()

Also make sure to check out Kostas Kremizas' tip about how you can pattern match directly against a member of URLError.

40 Making UIImage macOS compatible

🖥 Here's an easy way to make iOS model code that uses UIImage macOS compatible - like me and Gui Rambo discussed on the Swift by Sundell Podcast.

// Either put this in a separate file that you only include in your macOS target or wrap the code in #if os(macOS) / #endif

import Cocoa

// Step 1: Typealias UIImage to NSImage
typealias UIImage = NSImage

// Step 2: You might want to add these APIs that UIImage has but NSImage doesn't.
extension NSImage {
    var cgImage: CGImage? {
        var proposedRect = CGRect(origin: .zero, size: size)

        return cgImage(forProposedRect: &proposedRect,
                       context: nil,
                       hints: nil)
    }

    convenience init?(named name: String) {
        self.init(named: Name(name))
    }
}

// Step 3: Profit - you can now make your model code that uses UIImage cross-platform!
struct User {
    let name: String
    let profileImage: UIImage
}

39 Internally mutable protocol-oriented APIs

🤖 You can easily define a protocol-oriented API that can only be mutated internally, by using an internal protocol that extends a public one.

// Declare a public protocol that acts as your immutable API
public protocol ModelHolder {
    associatedtype Model
    var model: Model { get }
}

// Declare an extended, internal protocol that provides a mutable API
internal protocol MutableModelHolder: ModelHolder {
    var model: Model { get set }
}

// You can now implement the requirements using 'public internal(set)'
public class UserHolder: MutableModelHolder {
    public internal(set) var model: User

    internal init(model: User) {
        self.model = model
    }
}

38 Switching on a set

🎛 You can switch on a set using array literals as cases in Swift! Can be really useful to avoid many if/else if statements.

class RoadTile: Tile {
    var connectedDirections = Set<Direction>()

    func render() {
        switch connectedDirections {
        case [.up, .down]:
            image = UIImage(named: "road-vertical")
        case [.left, .right]:
            image = UIImage(named: "road-horizontal")
        default:
            image = UIImage(named: "road")
        }
    }
}

37 Adding the current locale to cache keys

🌍 When caching localized content in an app, it's a good idea to add the current locale to all keys, to prevent bugs when switching languages.

func cache(_ content: Content, forKey key: String) throws {
    let data = try wrap(content) as Data
    let key = localize(key: key)
    try storage.store(data, forKey: key)
}

func loadCachedContent(forKey key: String) -> Content? {
    let key = localize(key: key)
    let data = storage.loadData(forKey: key)
    return data.flatMap { try? unbox(data: $0) }
}

private func localize(key: String) -> String {
    return key + "-" + Bundle.main.preferredLocalizations[0]
}

36 Setting up tests to avoid retain cycles with weak references

🚳 Here's an easy way to setup a test to avoid accidental retain cycles with object relationships (like weak delegates & observers) in Swift:

func testDelegateNotRetained() {
    // Assign the delegate (weak) and also retain it using a local var
    var delegate: Delegate? = DelegateMock()
    controller.delegate = delegate
    XCTAssertNotNil(controller.delegate)
    
    // Release the local var, which should also release the weak reference
    delegate = nil
    XCTAssertNil(controller.delegate)
}

35 Expressively matching a value against a list of candidates

👨‍🔬 Playing around with an expressive way to check if a value matches any of a list of candidates in Swift:

// Instead of multiple conditions like this:

if string == "One" || string == "Two" || string == "Three" {

}

// You can now do:

if string == any(of: "One", "Two", "Three") {

}

You can find a gist with the implementation here.

34 Organizing code using extensions

👪 APIs in a Swift extension automatically inherit its access control level, making it a neat way to organize public, internal & private APIs.

public extension Animation {
    init(textureNamed textureName: String) {
        frames = [Texture(name: textureName)]
    }
    
    init(texturesNamed textureNames: [String], frameDuration: TimeInterval = 1) {
        frames = textureNames.map(Texture.init)
        self.frameDuration = frameDuration
    }
    
    init(image: Image) {
        frames = [Texture(image: image)]
    }
}

internal extension Animation {
    func loadFrameImages() -> [Image] {
        return frames.map { $0.loadImageIfNeeded() }
    }
}

33 Using map to transform an optional into a Result type

🗺 Using map you can transform an optional value into an optional Result type by simply passing in the enum case.

enum Result<Value> {
    case value(Value)
    case error(Error)
}

class Promise<Value> {
    private var result: Result<Value>?
    
    init(value: Value? = nil) {
        result = value.map(Result.value)
    }
}

32 Assigning to self in struct initializers

👌 It's so nice that you can assign directly to self in struct initializers in Swift. Very useful when adding conformance to protocols.

extension Bool: AnswerConvertible {
    public init(input: String) throws {
        switch input.lowercased() {
        case "y", "yes", "👍":
            self = true
        default:
            self = false
        }
    }
}

31 Recursively calling closures as inline functions

☎️ Defining Swift closures as inline functions enables you to recursively call them, which is super useful in things like custom sequences.

class Database {
    func records(matching query: Query) -> AnySequence<Record> {
        var recordIterator = loadRecords().makeIterator()
        
        func iterate() -> Record? {
            guard let nextRecord = recordIterator.next() else {
                return nil
            }
            
            guard nextRecord.matches(query) else {
                // Since the closure is an inline function, it can be recursively called,
                // in this case in order to advance to the next item.
                return iterate()
            }
            
            return nextRecord
        }
        
        // AnySequence/AnyIterator are part of the standard library and provide an easy way
        // to define custom sequences using closures.
        return AnySequence { AnyIterator(iterate) }
    }
}

Rob Napier points out that using the above might cause crashes if used on a large databaset, since Swift has no guaranteed Tail Call Optimization (TCO).

Slava Pestov also points out that another benefit of inline functions vs closures is that they can have their own generic parameter list.

30 Passing self to required Objective-C dependencies

🏖 Using lazy properties in Swift, you can pass self to required Objective-C dependencies without having to use force-unwrapped optionals.

class DataLoader: NSObject {
    lazy var urlSession: URLSession = self.makeURLSession()
    
    private func makeURLSession() -> URLSession {
        return URLSession(configuration: .default, delegate: self, delegateQueue: .main)
    }
}

class Renderer {
    lazy var displayLink: CADisplayLink = self.makeDisplayLink()
    
    private func makeDisplayLink() -> CADisplayLink {
        return CADisplayLink(target: self, selector: #selector(screenDidRefresh))
    }
}

29 Making weak or lazy properties readonly

👓 If you have a property in Swift that needs to be weak or lazy, you can still make it readonly by using private(set).

class Node {
    private(set) weak var parent: Node?
    private(set) lazy var children = [Node]()

    func add(child: Node) {
        children.append(child)
        child.parent = self
    }
}

28 Defining static URLs using string literals

🌏 Tired of using URL(string: "url")! for static URLs? Make URL conform to ExpressibleByStringLiteral and you can now simply use "url" instead.

extension URL: ExpressibleByStringLiteral {
    // By using 'StaticString' we disable string interpolation, for safety
    public init(stringLiteral value: StaticString) {
        self = URL(string: "\(value)").require(hint: "Invalid URL string literal: \(value)")
    }
}

// We can now define URLs using static string literals 🎉
let url: URL = "https://www.swiftbysundell.com"
let task = URLSession.shared.dataTask(with: "https://www.swiftbysundell.com")

// In Swift 3 or earlier, you also have to implement 2 additional initializers
extension URL {
    public init(extendedGraphemeClusterLiteral value: StaticString) {
        self.init(stringLiteral: value)
    }

    public init(unicodeScalarLiteral value: StaticString) {
        self.init(stringLiteral: value)
    }
}

To find the extension that adds the require() method on Optional that I use above, check out Require.

27 Manipulating points, sizes and frames using math operators

✚ I'm always careful with operator overloading, but for manipulating things like sizes, points & frames I find them super useful.

extension CGSize {
    static func *(lhs: CGSize, rhs: CGFloat) -> CGSize {
        return CGSize(width: lhs.width * rhs, height: lhs.height * rhs)
    }
}

button.frame.size = image.size * 2

If you like the above idea, check out CGOperators, which contains math operator overloads for all Core Graphics' vector types.

26 Using closure types in generic constraints

🔗 You can use closure types in generic constraints in Swift. Enables nice APIs for handling sequences of closures.

extension Sequence where Element == () -> Void {
    func callAll() {
        forEach { $0() }
    }
}

extension Sequence where Element == () -> String {
    func joinedResults(separator: String) -> String {
        return map { $0() }.joined(separator: separator)
    }
}

callbacks.callAll()
let names = nameProviders.joinedResults(separator: ", ")

(If you're using Swift 3, you have to change Element to Iterator.Element)

25 Using associated enum values to avoid state-specific optionals

🎉 Using associated enum values is a super nice way to encapsulate mutually exclusive state info (and avoiding state-specific optionals).

// BEFORE: Lots of state-specific, optional properties

class Player {
    var isWaitingForMatchMaking: Bool
    var invitingUser: User?
    var numberOfLives: Int
    var playerDefeatedBy: Player?
    var roundDefeatedIn: Int?
}

// AFTER: All state-specific information is encapsulated in enum cases

class Player {
    enum State {
        case waitingForMatchMaking
        case waitingForInviteResponse(from: User)
        case active(numberOfLives: Int)
        case defeated(by: Player, roundNumber: Int)
    }
    
    var state: State
}

24 Using enums for async result types

👍 I really like using enums for all async result types, even boolean ones. Self-documenting, and makes the call site a lot nicer to read too!

protocol PushNotificationService {
    // Before
    func enablePushNotifications(completionHandler: @escaping (Bool) -> Void)
    
    // After
    func enablePushNotifications(completionHandler: @escaping (PushNotificationStatus) -> Void)
}

enum PushNotificationStatus {
    case enabled
    case disabled
}

service.enablePushNotifications { status in
    if status == .enabled {
        enableNotificationsButton.removeFromSuperview()
    }
}

23 Working on async code in a playground

🏃 Want to work on your async code in a Swift Playground? Just set needsIndefiniteExecution to true to keep it running:

import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
    let greeting = "Hello after 3 seconds"
    print(greeting)
}

To stop the playground from executing, simply call PlaygroundPage.current.finishExecution().

22 Overriding self with a weak reference

💦 Avoid memory leaks when accidentially refering to self in closures by overriding it locally with a weak reference:

Swift >= 4.2

dataLoader.loadData(from: url) { [weak self] result in
    guard let self = self else { 
        return 
    }

    self.cache(result)
    
    ...

Swift < 4.2

dataLoader.loadData(from: url) { [weak self] result in
    guard let `self` = self else {
        return
    }

    self.cache(result)
    
    ...

Note that the reason the above currently works is because of a compiler bug (which I hope gets turned into a properly supported feature soon).

21 Using DispatchWorkItem

🕓 Using dispatch work items you can easily cancel a delayed asynchronous GCD task if you no longer need it:

let workItem = DispatchWorkItem {
    // Your async code goes in here
}

// Execute the work item after 1 second
DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: workItem)

// You can cancel the work item if you no longer need it
workItem.cancel()

20 Combining a sequence of functions

➕ While working on a new Swift developer tool (to be open sourced soon 😉), I came up with a pretty neat way of organizing its sequence of operations, by combining their functions into a closure:

internal func +<A, B, C>(lhs: @escaping (A) throws -> B,
                         rhs: @escaping (B) throws -> C) -> (A) throws -> C {
    return { try rhs(lhs($0)) }
}

public func run() throws {
    try (determineTarget + build + analyze + output)()
}

If you're familiar with the functional programming world, you might know the above technique as the pipe operator (thanks to Alexey Demedreckiy for pointing this out!)

19 Chaining optionals with map() and flatMap()

🗺 Using map() and flatMap() on optionals you can chain multiple operations without having to use lengthy if lets or guards:

// BEFORE

guard let string = argument(at: 1) else {
    return
}

guard let url = URL(string: string) else {
    return
}

handle(url)

// AFTER

argument(at: 1).flatMap(URL.init).map(handle)

18 Using self-executing closures for lazy properties

🚀 Using self-executing closures is a great way to encapsulate lazy property initialization:

class StoreViewController: UIViewController {
    private lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let view = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
        view.delegate = self
        view.dataSource = self
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(collectionView)
    }
}

17 Speeding up Swift package tests

⚡️ You can speed up your Swift package tests using the --parallel flag. For Marathon, the tests execute 3 times faster that way!

swift test --parallel

16 Avoiding mocking UserDefaults

🛠 Struggling with mocking UserDefaults in a test? The good news is: you don't need mocking - just create a real instance:

class LoginTests: XCTestCase {
    private var userDefaults: UserDefaults!
    private var manager: LoginManager!
    
    override func setUp() {
        super.setup()
        
        userDefaults = UserDefaults(suiteName: #file)
        userDefaults.removePersistentDomain(forName: #file)
        
        manager = LoginManager(userDefaults: userDefaults)
    }
}

15 Using variadic parameters

👍 Using variadic parameters in Swift, you can create some really nice APIs that take a list of objects without having to use an array:

extension Canvas {
    func add(_ shapes: Shape...) {
        shapes.forEach(add)
    }
}

let circle = Circle(center: CGPoint(x: 5, y: 5), radius: 5)
let lineA = Line(start: .zero, end: CGPoint(x: 10, y: 10))
let lineB = Line(start: CGPoint(x: 0, y: 10), end: CGPoint(x: 10, y: 0))

let canvas = Canvas()
canvas.add(circle, lineA, lineB)
canvas.render()

14 Referring to enum cases with associated values as closures

😮 Just like you can refer to a Swift function as a closure, you can do the same thing with enum cases with associated values:

enum UnboxPath {
    case key(String)
    case keyPath(String)
}

struct UserSchema {
    static let name = key("name")
    static let age = key("age")
    static let posts = key("posts")
    
    private static let key = UnboxPath.key
}

13 Using the === operator to compare objects by instance

📈 The === operator lets you check if two objects are the same instance. Very useful when verifying that an array contains an instance in a test:

protocol InstanceEquatable: class, Equatable {}

extension InstanceEquatable {
    static func ==(lhs: Self, rhs: Self) -> Bool {
        return lhs === rhs
    }
}

extension Enemy: InstanceEquatable {}

func testDestroyingEnemy() {
    player.attack(enemy)
    XCTAssertTrue(player.destroyedEnemies.contains(enemy))
}

12 Calling initializers with dot syntax and passing them as closures

😎 Cool thing about Swift initializers: you can call them using dot syntax and pass them as closures! Perfect for mocking dates in tests.

class Logger {
    private let storage: LogStorage
    private let dateProvider: () -> Date
    
    init(storage: LogStorage = .init(), dateProvider: @escaping () -> Date = Date.init) {
        self.storage = storage
        self.dateProvider = dateProvider
    }
    
    func log(event: Event) {
        storage.store(event: event, date: dateProvider())
    }
}

11 Structuring UI tests as extensions on XCUIApplication

📱 Most of my UI testing logic is now categories on XCUIApplication. Makes the test cases really easy to read:

func testLoggingInAndOut() {
    XCTAssertFalse(app.userIsLoggedIn)
    
    app.launch()
    app.login()
    XCTAssertTrue(app.userIsLoggedIn)
    
    app.logout()
    XCTAssertFalse(app.userIsLoggedIn)
}

func testDisplayingCategories() {
    XCTAssertFalse(app.isDisplayingCategories)
    
    app.launch()
    app.login()
    app.goToCategories()
    XCTAssertTrue(app.isDisplayingCategories)
}

10 Avoiding default cases in switch statements

🙂 It’s a good idea to avoid “default” cases when switching on Swift enums - it’ll “force you” to update your logic when a new case is added:

enum State {
    case loggedIn
    case loggedOut
    case onboarding
}

func handle(_ state: State) {
    switch state {
    case .loggedIn:
        showMainUI()
    case .loggedOut:
        showLoginUI()
    // Compiler error: Switch must be exhaustive
    }
}

9 Using the guard statement in many different scopes

💂 It's really cool that you can use Swift's 'guard' statement to exit out of pretty much any scope, not only return from functions:

// You can use the 'guard' statement to...

for string in strings {
    // ...continue an iteration
    guard shouldProcess(string) else {
        continue
    }
    
    // ...or break it
    guard !shouldBreak(for: string) else {
        break
    }
    
    // ...or return
    guard !shouldReturn(for: string) else {
        return
    }
    
    // ..or throw an error
    guard string.isValid else {
        throw StringError.invalid(string)
    }
    
    // ...or exit the program
    guard !shouldExit(for: string) else {
        exit(1)
    }
}

8 Passing functions & operators as closures

❤️ Love how you can pass functions & operators as closures in Swift. For example, it makes the syntax for sorting arrays really nice!

let array = [3, 9, 1, 4, 6, 2]
let sorted = array.sorted(by: <)

7 Using #function for UserDefaults key consistency

🗝 Here's a neat little trick I use to get UserDefault key consistency in Swift (#function expands to the property name in getters/setters). Just remember to write a good suite of tests that'll guard you against bugs when changing property names.

extension UserDefaults {
    var onboardingCompleted: Bool {
        get { return bool(forKey: #function) }
        set { set(newValue, forKey: #function) }
    }
}

6 Using a name already taken by the standard library

📛 Want to use a name already taken by the standard library for a nested type? No problem - just use Swift. to disambiguate:

extension Command {
    enum Error: Swift.Error {
        case missing
        case invalid(String)
    }
}

5 Using Wrap to implement Equatable

📦 Playing around with using Wrap to implement Equatable for any type, primarily for testing:

protocol AutoEquatable: Equatable {}

extension AutoEquatable {
    static func ==(lhs: Self, rhs: Self) -> Bool {
        let lhsData = try! wrap(lhs) as Data
        let rhsData = try! wrap(rhs) as Data
        return lhsData == rhsData
    }
}

4 Using typealiases to reduce the length of method signatures

📏 One thing that I find really useful in Swift is to use typealiases to reduce the length of method signatures in generic types:

public class PathFinder<Object: PathFinderObject> {
    public typealias Map = Object.Map
    public typealias Node = Map.Node
    public typealias Path = PathFinderPath<Object>
    
    public static func possiblePaths(for object: Object, at rootNode: Node, on map: Map) -> Path.Sequence {
        return .init(object: object, rootNode: rootNode, map: map)
    }
}

3 Referencing either external or internal parameter name when writing docs

📖 You can reference either the external or internal parameter label when writing Swift docs - and they get parsed the same:

// EITHER:

class Foo {
    /**
    *   - parameter string: A string
    */
    func bar(with string: String) {}
}

// OR:

class Foo {
    /**
    *   - parameter with: A string
    */
    func bar(with string: String) {}
}

2 Using auto closures

👍 Finding more and more uses for auto closures in Swift. Can enable some pretty nice APIs:

extension Dictionary {
    mutating func value(for key: Key, orAdd valueClosure: @autoclosure () -> Value) -> Value {
        if let value = self[key] {
            return value
        }
        
        let value = valueClosure()
        self[key] = value
        return value
    }
}

1 Namespacing with nested types

🚀 I’ve started to become a really big fan of nested types in Swift. Love the additional namespacing it gives you!

public struct Map {
    public struct Model {
        public let size: Size
        public let theme: Theme
        public var terrain: [Position : Terrain.Model]
        public var units: [Position : Unit.Model]
        public var buildings: [Position : Building.Model]
    }
    
    public enum Direction {
        case up
        case right
        case down
        case left
    }
    
    public struct Position {
        public var x: Int
        public var y: Int
    }
    
    public enum Size: String {
        case small = "S"
        case medium = "M"
        case large = "L"
        case extraLarge = "XL"
    }
}

Download Details:

Author: JohnSundell
Source Code: https://github.com/JohnSundell/SwiftTips 
License: MIT license

#swift #tips #tricks 

Nat  Grady

Nat Grady

1658734620

Chromium-net-errors: Chromium Network Errors for Node.js

Chromium Network Errors

Provides Chromium network errors found in net_error_list.h as custom error classes that can be conveniently used in Node.js, Electron apps and browsers.

The errors correspond to the error codes that are provided in Electron's did-fail-load events of the WebContents class and the webview tag.

Features

  • No dependencies.
  • 100% test coverage.
  • ES6 build with import and export, and a CommonJS build. Your bundler can use the ES6 modules if it supports the "module" or "jsnext:main" directives in the package.json.
  • Daily cron-triggered checks for updates on net_error_list.h on Travis CI to always get the most up-to-date list of errors.

Installation

npm install chromium-net-errors --save
import * as chromiumNetErrors from 'chromium-net-errors';
// or
const chromiumNetErrors = require('chromium-net-errors');

Example Use in Electron

import { app, BrowserWindow } from 'electron';
import * as chromiumNetErrors from 'chromium-net-errors';

app.on('ready', () => {
  const win = new BrowserWindow({
    width: 800,
    height: 600,
  });

  win.webContents.on('did-fail-load', (event) => {
    try {
      const Err = chromiumNetErrors.getErrorByCode(event.errorCode);
      throw new Err();
    } catch (err) {
      if (err instanceof chromiumNetErrors.NameNotResolvedError) {
        console.error(`The name '${event.validatedURL}' could not be resolved:\n  ${err.message}`);
      } else {
        console.error(`Something went wrong while loading ${event.validatedURL}`);
      }
    }
  });

  win.loadURL('http://blablanotexist.com');
});

Usage

import * as chromiumNetErrors from 'chromium-net-errors';

Create New Errors

const err = new chromiumNetErrors.ConnectionTimedOutError();

console.log(err instanceof Error);
// true
console.log(err instanceof chromiumNetErrors.ChromiumNetError);
// true
console.log(err instanceof chromiumNetErrors.ConnectionTimedOutError);
// true
function thrower() {
  throw new chromiumNetErrors.ConnectionTimedOutError();
}

try {
  thrower();
} catch (err) {
  console.log(err instanceof Error);
  // true
  console.log(err instanceof chromiumNetErrors.ChromiumNetError);
  // true
  console.log(err instanceof chromiumNetErrors.ConnectionTimedOutError);
  // true
}

Get Error by errorCode

Get the class of an error by its errorCode.

const Err = chromiumNetErrors.getErrorByCode(-201);
const err = new Err();

console.log(err instanceof chromiumNetErrors.CertDateInvalidError);
// true

console.log(err.isCertificateError());
// true

console.log(err.type); 
// 'certificate'

console.log(err.message);
// The server responded with a certificate that, by our clock, appears to
// either not yet be valid or to have expired. This could mean:
// 
// 1. An attacker is presenting an old certificate for which they have
// managed to obtain the private key.
// 
// 2. The server is misconfigured and is not presenting a valid cert.
// 
// 3. Our clock is wrong.

Get Error by errorDescription

Get the class of an error by its errorDescription.

const Err = chromiumNetErrors.getErrorByDescription('CERT_DATE_INVALID');
const err = new Err();

console.log(err instanceof chromiumNetErrors.CertDateInvalidError);
// true

console.log(err.isCertificateError());
// true

console.log(err.type); 
// 'certificate'

console.log(err.message);
// The server responded with a certificate that, by our clock, appears to
// either not yet be valid or to have expired. This could mean:
// 
// 1. An attacker is presenting an old certificate for which they have
// managed to obtain the private key.
// 
// 2. The server is misconfigured and is not presenting a valid cert.
// 
// 3. Our clock is wrong.

Get All Errors

Get an array of all possible errors.

console.log(chromiumNetErrors.getErrors());

// [ { name: 'IoPendingError',
//     code: -1,
//     description: 'IO_PENDING',
//     type: 'system',
//     message: 'An asynchronous IO operation is not yet complete.  This usually does not\nindicate a fatal error.  Typically this error will be generated as a\nnotification to wait for some external notification that the IO operation\nfinally completed.' },
//   { name: 'FailedError',
//     code: -2,
//     description: 'FAILED',
//     type: 'system',
//     message: 'A generic failure occurred.' },
//   { name: 'AbortedError',
//     code: -3,
//     description: 'ABORTED',
//     type: 'system',
//     message: 'An operation was aborted (due to user action).' },
//   { name: 'InvalidArgumentError',
//     code: -4,
//     description: 'INVALID_ARGUMENT',
//     type: 'system',
//     message: 'An argument to the function is incorrect.' },
//   { name: 'InvalidHandleError',
//     code: -5,
//     description: 'INVALID_HANDLE',
//     type: 'system',
//     message: 'The handle or file descriptor is invalid.' },
//   ...
// ]

List of Errors

IoPendingError

An asynchronous IO operation is not yet complete. This usually does not indicate a fatal error. Typically this error will be generated as a notification to wait for some external notification that the IO operation finally completed.

  • Name: IoPendingError
  • Code: -1
  • Description: IO_PENDING
  • Type: system
const err = new chromiumNetErrors.IoPendingError();
// or
const Err = chromiumNetErrors.getErrorByCode(-1);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('IO_PENDING');
const err = new Err();

FailedError

A generic failure occurred.

  • Name: FailedError
  • Code: -2
  • Description: FAILED
  • Type: system
const err = new chromiumNetErrors.FailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-2);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FAILED');
const err = new Err();

AbortedError

An operation was aborted (due to user action).

  • Name: AbortedError
  • Code: -3
  • Description: ABORTED
  • Type: system
const err = new chromiumNetErrors.AbortedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-3);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ABORTED');
const err = new Err();

InvalidArgumentError

An argument to the function is incorrect.

  • Name: InvalidArgumentError
  • Code: -4
  • Description: INVALID_ARGUMENT
  • Type: system
const err = new chromiumNetErrors.InvalidArgumentError();
// or
const Err = chromiumNetErrors.getErrorByCode(-4);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_ARGUMENT');
const err = new Err();

InvalidHandleError

The handle or file descriptor is invalid.

  • Name: InvalidHandleError
  • Code: -5
  • Description: INVALID_HANDLE
  • Type: system
const err = new chromiumNetErrors.InvalidHandleError();
// or
const Err = chromiumNetErrors.getErrorByCode(-5);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_HANDLE');
const err = new Err();

FileNotFoundError

The file or directory cannot be found.

  • Name: FileNotFoundError
  • Code: -6
  • Description: FILE_NOT_FOUND
  • Type: system
const err = new chromiumNetErrors.FileNotFoundError();
// or
const Err = chromiumNetErrors.getErrorByCode(-6);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FILE_NOT_FOUND');
const err = new Err();

TimedOutError

An operation timed out.

  • Name: TimedOutError
  • Code: -7
  • Description: TIMED_OUT
  • Type: system
const err = new chromiumNetErrors.TimedOutError();
// or
const Err = chromiumNetErrors.getErrorByCode(-7);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('TIMED_OUT');
const err = new Err();

FileTooBigError

The file is too large.

  • Name: FileTooBigError
  • Code: -8
  • Description: FILE_TOO_BIG
  • Type: system
const err = new chromiumNetErrors.FileTooBigError();
// or
const Err = chromiumNetErrors.getErrorByCode(-8);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FILE_TOO_BIG');
const err = new Err();

UnexpectedError

An unexpected error. This may be caused by a programming mistake or an invalid assumption.

  • Name: UnexpectedError
  • Code: -9
  • Description: UNEXPECTED
  • Type: system
const err = new chromiumNetErrors.UnexpectedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-9);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNEXPECTED');
const err = new Err();

AccessDeniedError

Permission to access a resource, other than the network, was denied.

  • Name: AccessDeniedError
  • Code: -10
  • Description: ACCESS_DENIED
  • Type: system
const err = new chromiumNetErrors.AccessDeniedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-10);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ACCESS_DENIED');
const err = new Err();

NotImplementedError

The operation failed because of unimplemented functionality.

  • Name: NotImplementedError
  • Code: -11
  • Description: NOT_IMPLEMENTED
  • Type: system
const err = new chromiumNetErrors.NotImplementedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-11);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NOT_IMPLEMENTED');
const err = new Err();

InsufficientResourcesError

There were not enough resources to complete the operation.

  • Name: InsufficientResourcesError
  • Code: -12
  • Description: INSUFFICIENT_RESOURCES
  • Type: system
const err = new chromiumNetErrors.InsufficientResourcesError();
// or
const Err = chromiumNetErrors.getErrorByCode(-12);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INSUFFICIENT_RESOURCES');
const err = new Err();

OutOfMemoryError

Memory allocation failed.

  • Name: OutOfMemoryError
  • Code: -13
  • Description: OUT_OF_MEMORY
  • Type: system
const err = new chromiumNetErrors.OutOfMemoryError();
// or
const Err = chromiumNetErrors.getErrorByCode(-13);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('OUT_OF_MEMORY');
const err = new Err();

UploadFileChangedError

The file upload failed because the file's modification time was different from the expectation.

  • Name: UploadFileChangedError
  • Code: -14
  • Description: UPLOAD_FILE_CHANGED
  • Type: system
const err = new chromiumNetErrors.UploadFileChangedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-14);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UPLOAD_FILE_CHANGED');
const err = new Err();

SocketNotConnectedError

The socket is not connected.

  • Name: SocketNotConnectedError
  • Code: -15
  • Description: SOCKET_NOT_CONNECTED
  • Type: system
const err = new chromiumNetErrors.SocketNotConnectedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-15);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SOCKET_NOT_CONNECTED');
const err = new Err();

FileExistsError

The file already exists.

  • Name: FileExistsError
  • Code: -16
  • Description: FILE_EXISTS
  • Type: system
const err = new chromiumNetErrors.FileExistsError();
// or
const Err = chromiumNetErrors.getErrorByCode(-16);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FILE_EXISTS');
const err = new Err();

FilePathTooLongError

The path or file name is too long.

  • Name: FilePathTooLongError
  • Code: -17
  • Description: FILE_PATH_TOO_LONG
  • Type: system
const err = new chromiumNetErrors.FilePathTooLongError();
// or
const Err = chromiumNetErrors.getErrorByCode(-17);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FILE_PATH_TOO_LONG');
const err = new Err();

FileNoSpaceError

Not enough room left on the disk.

  • Name: FileNoSpaceError
  • Code: -18
  • Description: FILE_NO_SPACE
  • Type: system
const err = new chromiumNetErrors.FileNoSpaceError();
// or
const Err = chromiumNetErrors.getErrorByCode(-18);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FILE_NO_SPACE');
const err = new Err();

FileVirusInfectedError

The file has a virus.

  • Name: FileVirusInfectedError
  • Code: -19
  • Description: FILE_VIRUS_INFECTED
  • Type: system
const err = new chromiumNetErrors.FileVirusInfectedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-19);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FILE_VIRUS_INFECTED');
const err = new Err();

BlockedByClientError

The client chose to block the request.

  • Name: BlockedByClientError
  • Code: -20
  • Description: BLOCKED_BY_CLIENT
  • Type: system
const err = new chromiumNetErrors.BlockedByClientError();
// or
const Err = chromiumNetErrors.getErrorByCode(-20);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('BLOCKED_BY_CLIENT');
const err = new Err();

NetworkChangedError

The network changed.

  • Name: NetworkChangedError
  • Code: -21
  • Description: NETWORK_CHANGED
  • Type: system
const err = new chromiumNetErrors.NetworkChangedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-21);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NETWORK_CHANGED');
const err = new Err();

BlockedByAdministratorError

The request was blocked by the URL block list configured by the domain administrator.

  • Name: BlockedByAdministratorError
  • Code: -22
  • Description: BLOCKED_BY_ADMINISTRATOR
  • Type: system
const err = new chromiumNetErrors.BlockedByAdministratorError();
// or
const Err = chromiumNetErrors.getErrorByCode(-22);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('BLOCKED_BY_ADMINISTRATOR');
const err = new Err();

SocketIsConnectedError

The socket is already connected.

  • Name: SocketIsConnectedError
  • Code: -23
  • Description: SOCKET_IS_CONNECTED
  • Type: system
const err = new chromiumNetErrors.SocketIsConnectedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-23);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SOCKET_IS_CONNECTED');
const err = new Err();

BlockedEnrollmentCheckPendingError

The request was blocked because the forced reenrollment check is still pending. This error can only occur on ChromeOS. The error can be emitted by code in chrome/browser/policy/policy_helpers.cc.

  • Name: BlockedEnrollmentCheckPendingError
  • Code: -24
  • Description: BLOCKED_ENROLLMENT_CHECK_PENDING
  • Type: system
const err = new chromiumNetErrors.BlockedEnrollmentCheckPendingError();
// or
const Err = chromiumNetErrors.getErrorByCode(-24);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('BLOCKED_ENROLLMENT_CHECK_PENDING');
const err = new Err();

UploadStreamRewindNotSupportedError

The upload failed because the upload stream needed to be re-read, due to a retry or a redirect, but the upload stream doesn't support that operation.

  • Name: UploadStreamRewindNotSupportedError
  • Code: -25
  • Description: UPLOAD_STREAM_REWIND_NOT_SUPPORTED
  • Type: system
const err = new chromiumNetErrors.UploadStreamRewindNotSupportedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-25);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UPLOAD_STREAM_REWIND_NOT_SUPPORTED');
const err = new Err();

ContextShutDownError

The request failed because the URLRequestContext is shutting down, or has been shut down.

  • Name: ContextShutDownError
  • Code: -26
  • Description: CONTEXT_SHUT_DOWN
  • Type: system
const err = new chromiumNetErrors.ContextShutDownError();
// or
const Err = chromiumNetErrors.getErrorByCode(-26);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONTEXT_SHUT_DOWN');
const err = new Err();

BlockedByResponseError

The request failed because the response was delivered along with requirements which are not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks and 'Cross-Origin-Resource-Policy', for instance).

  • Name: BlockedByResponseError
  • Code: -27
  • Description: BLOCKED_BY_RESPONSE
  • Type: system
const err = new chromiumNetErrors.BlockedByResponseError();
// or
const Err = chromiumNetErrors.getErrorByCode(-27);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('BLOCKED_BY_RESPONSE');
const err = new Err();

CleartextNotPermittedError

The request was blocked by system policy disallowing some or all cleartext requests. Used for NetworkSecurityPolicy on Android.

  • Name: CleartextNotPermittedError
  • Code: -29
  • Description: CLEARTEXT_NOT_PERMITTED
  • Type: system
const err = new chromiumNetErrors.CleartextNotPermittedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-29);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CLEARTEXT_NOT_PERMITTED');
const err = new Err();

BlockedByCspError

The request was blocked by a Content Security Policy

  • Name: BlockedByCspError
  • Code: -30
  • Description: BLOCKED_BY_CSP
  • Type: system
const err = new chromiumNetErrors.BlockedByCspError();
// or
const Err = chromiumNetErrors.getErrorByCode(-30);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('BLOCKED_BY_CSP');
const err = new Err();

H2OrQuicRequiredError

The request was blocked because of no H/2 or QUIC session.

  • Name: H2OrQuicRequiredError
  • Code: -31
  • Description: H2_OR_QUIC_REQUIRED
  • Type: system
const err = new chromiumNetErrors.H2OrQuicRequiredError();
// or
const Err = chromiumNetErrors.getErrorByCode(-31);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('H2_OR_QUIC_REQUIRED');
const err = new Err();

ConnectionClosedError

A connection was closed (corresponding to a TCP FIN).

  • Name: ConnectionClosedError
  • Code: -100
  • Description: CONNECTION_CLOSED
  • Type: connection
const err = new chromiumNetErrors.ConnectionClosedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-100);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONNECTION_CLOSED');
const err = new Err();

ConnectionResetError

A connection was reset (corresponding to a TCP RST).

  • Name: ConnectionResetError
  • Code: -101
  • Description: CONNECTION_RESET
  • Type: connection
const err = new chromiumNetErrors.ConnectionResetError();
// or
const Err = chromiumNetErrors.getErrorByCode(-101);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONNECTION_RESET');
const err = new Err();

ConnectionRefusedError

A connection attempt was refused.

  • Name: ConnectionRefusedError
  • Code: -102
  • Description: CONNECTION_REFUSED
  • Type: connection
const err = new chromiumNetErrors.ConnectionRefusedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-102);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONNECTION_REFUSED');
const err = new Err();

ConnectionAbortedError

A connection timed out as a result of not receiving an ACK for data sent. This can include a FIN packet that did not get ACK'd.

  • Name: ConnectionAbortedError
  • Code: -103
  • Description: CONNECTION_ABORTED
  • Type: connection
const err = new chromiumNetErrors.ConnectionAbortedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-103);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONNECTION_ABORTED');
const err = new Err();

ConnectionFailedError

A connection attempt failed.

  • Name: ConnectionFailedError
  • Code: -104
  • Description: CONNECTION_FAILED
  • Type: connection
const err = new chromiumNetErrors.ConnectionFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-104);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONNECTION_FAILED');
const err = new Err();

NameNotResolvedError

The host name could not be resolved.

  • Name: NameNotResolvedError
  • Code: -105
  • Description: NAME_NOT_RESOLVED
  • Type: connection
const err = new chromiumNetErrors.NameNotResolvedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-105);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NAME_NOT_RESOLVED');
const err = new Err();

InternetDisconnectedError

The Internet connection has been lost.

  • Name: InternetDisconnectedError
  • Code: -106
  • Description: INTERNET_DISCONNECTED
  • Type: connection
const err = new chromiumNetErrors.InternetDisconnectedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-106);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INTERNET_DISCONNECTED');
const err = new Err();

SslProtocolError

An SSL protocol error occurred.

  • Name: SslProtocolError
  • Code: -107
  • Description: SSL_PROTOCOL_ERROR
  • Type: connection
const err = new chromiumNetErrors.SslProtocolError();
// or
const Err = chromiumNetErrors.getErrorByCode(-107);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_PROTOCOL_ERROR');
const err = new Err();

AddressInvalidError

The IP address or port number is invalid (e.g., cannot connect to the IP address 0 or the port 0).

  • Name: AddressInvalidError
  • Code: -108
  • Description: ADDRESS_INVALID
  • Type: connection
const err = new chromiumNetErrors.AddressInvalidError();
// or
const Err = chromiumNetErrors.getErrorByCode(-108);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ADDRESS_INVALID');
const err = new Err();

AddressUnreachableError

The IP address is unreachable. This usually means that there is no route to the specified host or network.

  • Name: AddressUnreachableError
  • Code: -109
  • Description: ADDRESS_UNREACHABLE
  • Type: connection
const err = new chromiumNetErrors.AddressUnreachableError();
// or
const Err = chromiumNetErrors.getErrorByCode(-109);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ADDRESS_UNREACHABLE');
const err = new Err();

SslClientAuthCertNeededError

The server requested a client certificate for SSL client authentication.

  • Name: SslClientAuthCertNeededError
  • Code: -110
  • Description: SSL_CLIENT_AUTH_CERT_NEEDED
  • Type: connection
const err = new chromiumNetErrors.SslClientAuthCertNeededError();
// or
const Err = chromiumNetErrors.getErrorByCode(-110);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_CLIENT_AUTH_CERT_NEEDED');
const err = new Err();

TunnelConnectionFailedError

A tunnel connection through the proxy could not be established.

  • Name: TunnelConnectionFailedError
  • Code: -111
  • Description: TUNNEL_CONNECTION_FAILED
  • Type: connection
const err = new chromiumNetErrors.TunnelConnectionFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-111);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('TUNNEL_CONNECTION_FAILED');
const err = new Err();

NoSslVersionsEnabledError

No SSL protocol versions are enabled.

  • Name: NoSslVersionsEnabledError
  • Code: -112
  • Description: NO_SSL_VERSIONS_ENABLED
  • Type: connection
const err = new chromiumNetErrors.NoSslVersionsEnabledError();
// or
const Err = chromiumNetErrors.getErrorByCode(-112);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NO_SSL_VERSIONS_ENABLED');
const err = new Err();

SslVersionOrCipherMismatchError

The client and server don't support a common SSL protocol version or cipher suite.

  • Name: SslVersionOrCipherMismatchError
  • Code: -113
  • Description: SSL_VERSION_OR_CIPHER_MISMATCH
  • Type: connection
const err = new chromiumNetErrors.SslVersionOrCipherMismatchError();
// or
const Err = chromiumNetErrors.getErrorByCode(-113);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_VERSION_OR_CIPHER_MISMATCH');
const err = new Err();

SslRenegotiationRequestedError

The server requested a renegotiation (rehandshake).

  • Name: SslRenegotiationRequestedError
  • Code: -114
  • Description: SSL_RENEGOTIATION_REQUESTED
  • Type: connection
const err = new chromiumNetErrors.SslRenegotiationRequestedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-114);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_RENEGOTIATION_REQUESTED');
const err = new Err();

ProxyAuthUnsupportedError

The proxy requested authentication (for tunnel establishment) with an unsupported method.

  • Name: ProxyAuthUnsupportedError
  • Code: -115
  • Description: PROXY_AUTH_UNSUPPORTED
  • Type: connection
const err = new chromiumNetErrors.ProxyAuthUnsupportedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-115);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PROXY_AUTH_UNSUPPORTED');
const err = new Err();

CertErrorInSslRenegotiationError

During SSL renegotiation (rehandshake), the server sent a certificate with an error.

Note: this error is not in the -2xx range so that it won't be handled as a certificate error.

  • Name: CertErrorInSslRenegotiationError
  • Code: -116
  • Description: CERT_ERROR_IN_SSL_RENEGOTIATION
  • Type: connection
const err = new chromiumNetErrors.CertErrorInSslRenegotiationError();
// or
const Err = chromiumNetErrors.getErrorByCode(-116);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_ERROR_IN_SSL_RENEGOTIATION');
const err = new Err();

BadSslClientAuthCertError

The SSL handshake failed because of a bad or missing client certificate.

  • Name: BadSslClientAuthCertError
  • Code: -117
  • Description: BAD_SSL_CLIENT_AUTH_CERT
  • Type: connection
const err = new chromiumNetErrors.BadSslClientAuthCertError();
// or
const Err = chromiumNetErrors.getErrorByCode(-117);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('BAD_SSL_CLIENT_AUTH_CERT');
const err = new Err();

ConnectionTimedOutError

A connection attempt timed out.

  • Name: ConnectionTimedOutError
  • Code: -118
  • Description: CONNECTION_TIMED_OUT
  • Type: connection
const err = new chromiumNetErrors.ConnectionTimedOutError();
// or
const Err = chromiumNetErrors.getErrorByCode(-118);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONNECTION_TIMED_OUT');
const err = new Err();

HostResolverQueueTooLargeError

There are too many pending DNS resolves, so a request in the queue was aborted.

  • Name: HostResolverQueueTooLargeError
  • Code: -119
  • Description: HOST_RESOLVER_QUEUE_TOO_LARGE
  • Type: connection
const err = new chromiumNetErrors.HostResolverQueueTooLargeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-119);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HOST_RESOLVER_QUEUE_TOO_LARGE');
const err = new Err();

SocksConnectionFailedError

Failed establishing a connection to the SOCKS proxy server for a target host.

  • Name: SocksConnectionFailedError
  • Code: -120
  • Description: SOCKS_CONNECTION_FAILED
  • Type: connection
const err = new chromiumNetErrors.SocksConnectionFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-120);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SOCKS_CONNECTION_FAILED');
const err = new Err();

SocksConnectionHostUnreachableError

The SOCKS proxy server failed establishing connection to the target host because that host is unreachable.

  • Name: SocksConnectionHostUnreachableError
  • Code: -121
  • Description: SOCKS_CONNECTION_HOST_UNREACHABLE
  • Type: connection
const err = new chromiumNetErrors.SocksConnectionHostUnreachableError();
// or
const Err = chromiumNetErrors.getErrorByCode(-121);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SOCKS_CONNECTION_HOST_UNREACHABLE');
const err = new Err();

AlpnNegotiationFailedError

The request to negotiate an alternate protocol failed.

  • Name: AlpnNegotiationFailedError
  • Code: -122
  • Description: ALPN_NEGOTIATION_FAILED
  • Type: connection
const err = new chromiumNetErrors.AlpnNegotiationFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-122);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ALPN_NEGOTIATION_FAILED');
const err = new Err();

SslNoRenegotiationError

The peer sent an SSL no_renegotiation alert message.

  • Name: SslNoRenegotiationError
  • Code: -123
  • Description: SSL_NO_RENEGOTIATION
  • Type: connection
const err = new chromiumNetErrors.SslNoRenegotiationError();
// or
const Err = chromiumNetErrors.getErrorByCode(-123);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_NO_RENEGOTIATION');
const err = new Err();

WinsockUnexpectedWrittenBytesError

Winsock sometimes reports more data written than passed. This is probably due to a broken LSP.

  • Name: WinsockUnexpectedWrittenBytesError
  • Code: -124
  • Description: WINSOCK_UNEXPECTED_WRITTEN_BYTES
  • Type: connection
const err = new chromiumNetErrors.WinsockUnexpectedWrittenBytesError();
// or
const Err = chromiumNetErrors.getErrorByCode(-124);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('WINSOCK_UNEXPECTED_WRITTEN_BYTES');
const err = new Err();

SslDecompressionFailureAlertError

An SSL peer sent us a fatal decompression_failure alert. This typically occurs when a peer selects DEFLATE compression in the mistaken belief that it supports it.

  • Name: SslDecompressionFailureAlertError
  • Code: -125
  • Description: SSL_DECOMPRESSION_FAILURE_ALERT
  • Type: connection
const err = new chromiumNetErrors.SslDecompressionFailureAlertError();
// or
const Err = chromiumNetErrors.getErrorByCode(-125);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_DECOMPRESSION_FAILURE_ALERT');
const err = new Err();

SslBadRecordMacAlertError

An SSL peer sent us a fatal bad_record_mac alert. This has been observed from servers with buggy DEFLATE support.

  • Name: SslBadRecordMacAlertError
  • Code: -126
  • Description: SSL_BAD_RECORD_MAC_ALERT
  • Type: connection
const err = new chromiumNetErrors.SslBadRecordMacAlertError();
// or
const Err = chromiumNetErrors.getErrorByCode(-126);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_BAD_RECORD_MAC_ALERT');
const err = new Err();

ProxyAuthRequestedError

The proxy requested authentication (for tunnel establishment).

  • Name: ProxyAuthRequestedError
  • Code: -127
  • Description: PROXY_AUTH_REQUESTED
  • Type: connection
const err = new chromiumNetErrors.ProxyAuthRequestedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-127);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PROXY_AUTH_REQUESTED');
const err = new Err();

ProxyConnectionFailedError

Could not create a connection to the proxy server. An error occurred either in resolving its name, or in connecting a socket to it. Note that this does NOT include failures during the actual "CONNECT" method of an HTTP proxy.

  • Name: ProxyConnectionFailedError
  • Code: -130
  • Description: PROXY_CONNECTION_FAILED
  • Type: connection
const err = new chromiumNetErrors.ProxyConnectionFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-130);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PROXY_CONNECTION_FAILED');
const err = new Err();

MandatoryProxyConfigurationFailedError

A mandatory proxy configuration could not be used. Currently this means that a mandatory PAC script could not be fetched, parsed or executed.

  • Name: MandatoryProxyConfigurationFailedError
  • Code: -131
  • Description: MANDATORY_PROXY_CONFIGURATION_FAILED
  • Type: connection
const err = new chromiumNetErrors.MandatoryProxyConfigurationFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-131);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('MANDATORY_PROXY_CONFIGURATION_FAILED');
const err = new Err();

PreconnectMaxSocketLimitError

We've hit the max socket limit for the socket pool while preconnecting. We don't bother trying to preconnect more sockets.

  • Name: PreconnectMaxSocketLimitError
  • Code: -133
  • Description: PRECONNECT_MAX_SOCKET_LIMIT
  • Type: connection
const err = new chromiumNetErrors.PreconnectMaxSocketLimitError();
// or
const Err = chromiumNetErrors.getErrorByCode(-133);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PRECONNECT_MAX_SOCKET_LIMIT');
const err = new Err();

SslClientAuthPrivateKeyAccessDeniedError

The permission to use the SSL client certificate's private key was denied.

  • Name: SslClientAuthPrivateKeyAccessDeniedError
  • Code: -134
  • Description: SSL_CLIENT_AUTH_PRIVATE_KEY_ACCESS_DENIED
  • Type: connection
const err = new chromiumNetErrors.SslClientAuthPrivateKeyAccessDeniedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-134);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_CLIENT_AUTH_PRIVATE_KEY_ACCESS_DENIED');
const err = new Err();

SslClientAuthCertNoPrivateKeyError

The SSL client certificate has no private key.

  • Name: SslClientAuthCertNoPrivateKeyError
  • Code: -135
  • Description: SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
  • Type: connection
const err = new chromiumNetErrors.SslClientAuthCertNoPrivateKeyError();
// or
const Err = chromiumNetErrors.getErrorByCode(-135);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY');
const err = new Err();

ProxyCertificateInvalidError

The certificate presented by the HTTPS Proxy was invalid.

  • Name: ProxyCertificateInvalidError
  • Code: -136
  • Description: PROXY_CERTIFICATE_INVALID
  • Type: connection
const err = new chromiumNetErrors.ProxyCertificateInvalidError();
// or
const Err = chromiumNetErrors.getErrorByCode(-136);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PROXY_CERTIFICATE_INVALID');
const err = new Err();

NameResolutionFailedError

An error occurred when trying to do a name resolution (DNS).

  • Name: NameResolutionFailedError
  • Code: -137
  • Description: NAME_RESOLUTION_FAILED
  • Type: connection
const err = new chromiumNetErrors.NameResolutionFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-137);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NAME_RESOLUTION_FAILED');
const err = new Err();

NetworkAccessDeniedError

Permission to access the network was denied. This is used to distinguish errors that were most likely caused by a firewall from other access denied errors. See also ERR_ACCESS_DENIED.

  • Name: NetworkAccessDeniedError
  • Code: -138
  • Description: NETWORK_ACCESS_DENIED
  • Type: connection
const err = new chromiumNetErrors.NetworkAccessDeniedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-138);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NETWORK_ACCESS_DENIED');
const err = new Err();

TemporarilyThrottledError

The request throttler module cancelled this request to avoid DDOS.

  • Name: TemporarilyThrottledError
  • Code: -139
  • Description: TEMPORARILY_THROTTLED
  • Type: connection
const err = new chromiumNetErrors.TemporarilyThrottledError();
// or
const Err = chromiumNetErrors.getErrorByCode(-139);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('TEMPORARILY_THROTTLED');
const err = new Err();

HttpsProxyTunnelResponseRedirectError

A request to create an SSL tunnel connection through the HTTPS proxy received a 302 (temporary redirect) response. The response body might include a description of why the request failed.

TODO(https://crbug.com/928551): This is deprecated and should not be used by new code.

  • Name: HttpsProxyTunnelResponseRedirectError
  • Code: -140
  • Description: HTTPS_PROXY_TUNNEL_RESPONSE_REDIRECT
  • Type: connection
const err = new chromiumNetErrors.HttpsProxyTunnelResponseRedirectError();
// or
const Err = chromiumNetErrors.getErrorByCode(-140);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTPS_PROXY_TUNNEL_RESPONSE_REDIRECT');
const err = new Err();

SslClientAuthSignatureFailedError

We were unable to sign the CertificateVerify data of an SSL client auth handshake with the client certificate's private key.

Possible causes for this include the user implicitly or explicitly denying access to the private key, the private key may not be valid for signing, the key may be relying on a cached handle which is no longer valid, or the CSP won't allow arbitrary data to be signed.

  • Name: SslClientAuthSignatureFailedError
  • Code: -141
  • Description: SSL_CLIENT_AUTH_SIGNATURE_FAILED
  • Type: connection
const err = new chromiumNetErrors.SslClientAuthSignatureFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-141);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_CLIENT_AUTH_SIGNATURE_FAILED');
const err = new Err();

MsgTooBigError

The message was too large for the transport. (for example a UDP message which exceeds size threshold).

  • Name: MsgTooBigError
  • Code: -142
  • Description: MSG_TOO_BIG
  • Type: connection
const err = new chromiumNetErrors.MsgTooBigError();
// or
const Err = chromiumNetErrors.getErrorByCode(-142);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('MSG_TOO_BIG');
const err = new Err();

WsProtocolError

Websocket protocol error. Indicates that we are terminating the connection due to a malformed frame or other protocol violation.

  • Name: WsProtocolError
  • Code: -145
  • Description: WS_PROTOCOL_ERROR
  • Type: connection
const err = new chromiumNetErrors.WsProtocolError();
// or
const Err = chromiumNetErrors.getErrorByCode(-145);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('WS_PROTOCOL_ERROR');
const err = new Err();

AddressInUseError

Returned when attempting to bind an address that is already in use.

  • Name: AddressInUseError
  • Code: -147
  • Description: ADDRESS_IN_USE
  • Type: connection
const err = new chromiumNetErrors.AddressInUseError();
// or
const Err = chromiumNetErrors.getErrorByCode(-147);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ADDRESS_IN_USE');
const err = new Err();

SslHandshakeNotCompletedError

An operation failed because the SSL handshake has not completed.

  • Name: SslHandshakeNotCompletedError
  • Code: -148
  • Description: SSL_HANDSHAKE_NOT_COMPLETED
  • Type: connection
const err = new chromiumNetErrors.SslHandshakeNotCompletedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-148);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_HANDSHAKE_NOT_COMPLETED');
const err = new Err();

SslBadPeerPublicKeyError

SSL peer's public key is invalid.

  • Name: SslBadPeerPublicKeyError
  • Code: -149
  • Description: SSL_BAD_PEER_PUBLIC_KEY
  • Type: connection
const err = new chromiumNetErrors.SslBadPeerPublicKeyError();
// or
const Err = chromiumNetErrors.getErrorByCode(-149);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_BAD_PEER_PUBLIC_KEY');
const err = new Err();

SslPinnedKeyNotInCertChainError

The certificate didn't match the built-in public key pins for the host name. The pins are set in net/http/transport_security_state.cc and require that one of a set of public keys exist on the path from the leaf to the root.

  • Name: SslPinnedKeyNotInCertChainError
  • Code: -150
  • Description: SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
  • Type: connection
const err = new chromiumNetErrors.SslPinnedKeyNotInCertChainError();
// or
const Err = chromiumNetErrors.getErrorByCode(-150);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_PINNED_KEY_NOT_IN_CERT_CHAIN');
const err = new Err();

ClientAuthCertTypeUnsupportedError

Server request for client certificate did not contain any types we support.

  • Name: ClientAuthCertTypeUnsupportedError
  • Code: -151
  • Description: CLIENT_AUTH_CERT_TYPE_UNSUPPORTED
  • Type: connection
const err = new chromiumNetErrors.ClientAuthCertTypeUnsupportedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-151);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CLIENT_AUTH_CERT_TYPE_UNSUPPORTED');
const err = new Err();

SslDecryptErrorAlertError

An SSL peer sent us a fatal decrypt_error alert. This typically occurs when a peer could not correctly verify a signature (in CertificateVerify or ServerKeyExchange) or validate a Finished message.

  • Name: SslDecryptErrorAlertError
  • Code: -153
  • Description: SSL_DECRYPT_ERROR_ALERT
  • Type: connection
const err = new chromiumNetErrors.SslDecryptErrorAlertError();
// or
const Err = chromiumNetErrors.getErrorByCode(-153);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_DECRYPT_ERROR_ALERT');
const err = new Err();

WsThrottleQueueTooLargeError

There are too many pending WebSocketJob instances, so the new job was not pushed to the queue.

  • Name: WsThrottleQueueTooLargeError
  • Code: -154
  • Description: WS_THROTTLE_QUEUE_TOO_LARGE
  • Type: connection
const err = new chromiumNetErrors.WsThrottleQueueTooLargeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-154);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('WS_THROTTLE_QUEUE_TOO_LARGE');
const err = new Err();

SslServerCertChangedError

The SSL server certificate changed in a renegotiation.

  • Name: SslServerCertChangedError
  • Code: -156
  • Description: SSL_SERVER_CERT_CHANGED
  • Type: connection
const err = new chromiumNetErrors.SslServerCertChangedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-156);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_SERVER_CERT_CHANGED');
const err = new Err();

SslUnrecognizedNameAlertError

The SSL server sent us a fatal unrecognized_name alert.

  • Name: SslUnrecognizedNameAlertError
  • Code: -159
  • Description: SSL_UNRECOGNIZED_NAME_ALERT
  • Type: connection
const err = new chromiumNetErrors.SslUnrecognizedNameAlertError();
// or
const Err = chromiumNetErrors.getErrorByCode(-159);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_UNRECOGNIZED_NAME_ALERT');
const err = new Err();

SocketSetReceiveBufferSizeError

Failed to set the socket's receive buffer size as requested.

  • Name: SocketSetReceiveBufferSizeError
  • Code: -160
  • Description: SOCKET_SET_RECEIVE_BUFFER_SIZE_ERROR
  • Type: connection
const err = new chromiumNetErrors.SocketSetReceiveBufferSizeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-160);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SOCKET_SET_RECEIVE_BUFFER_SIZE_ERROR');
const err = new Err();

SocketSetSendBufferSizeError

Failed to set the socket's send buffer size as requested.

  • Name: SocketSetSendBufferSizeError
  • Code: -161
  • Description: SOCKET_SET_SEND_BUFFER_SIZE_ERROR
  • Type: connection
const err = new chromiumNetErrors.SocketSetSendBufferSizeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-161);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SOCKET_SET_SEND_BUFFER_SIZE_ERROR');
const err = new Err();

SocketReceiveBufferSizeUnchangeableError

Failed to set the socket's receive buffer size as requested, despite success return code from setsockopt.

  • Name: SocketReceiveBufferSizeUnchangeableError
  • Code: -162
  • Description: SOCKET_RECEIVE_BUFFER_SIZE_UNCHANGEABLE
  • Type: connection
const err = new chromiumNetErrors.SocketReceiveBufferSizeUnchangeableError();
// or
const Err = chromiumNetErrors.getErrorByCode(-162);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SOCKET_RECEIVE_BUFFER_SIZE_UNCHANGEABLE');
const err = new Err();

SocketSendBufferSizeUnchangeableError

Failed to set the socket's send buffer size as requested, despite success return code from setsockopt.

  • Name: SocketSendBufferSizeUnchangeableError
  • Code: -163
  • Description: SOCKET_SEND_BUFFER_SIZE_UNCHANGEABLE
  • Type: connection
const err = new chromiumNetErrors.SocketSendBufferSizeUnchangeableError();
// or
const Err = chromiumNetErrors.getErrorByCode(-163);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SOCKET_SEND_BUFFER_SIZE_UNCHANGEABLE');
const err = new Err();

SslClientAuthCertBadFormatError

Failed to import a client certificate from the platform store into the SSL library.

  • Name: SslClientAuthCertBadFormatError
  • Code: -164
  • Description: SSL_CLIENT_AUTH_CERT_BAD_FORMAT
  • Type: connection
const err = new chromiumNetErrors.SslClientAuthCertBadFormatError();
// or
const Err = chromiumNetErrors.getErrorByCode(-164);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_CLIENT_AUTH_CERT_BAD_FORMAT');
const err = new Err();

IcannNameCollisionError

Resolving a hostname to an IP address list included the IPv4 address "127.0.53.53". This is a special IP address which ICANN has recommended to indicate there was a name collision, and alert admins to a potential problem.

  • Name: IcannNameCollisionError
  • Code: -166
  • Description: ICANN_NAME_COLLISION
  • Type: connection
const err = new chromiumNetErrors.IcannNameCollisionError();
// or
const Err = chromiumNetErrors.getErrorByCode(-166);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ICANN_NAME_COLLISION');
const err = new Err();

SslServerCertBadFormatError

The SSL server presented a certificate which could not be decoded. This is not a certificate error code as no X509Certificate object is available. This error is fatal.

  • Name: SslServerCertBadFormatError
  • Code: -167
  • Description: SSL_SERVER_CERT_BAD_FORMAT
  • Type: connection
const err = new chromiumNetErrors.SslServerCertBadFormatError();
// or
const Err = chromiumNetErrors.getErrorByCode(-167);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_SERVER_CERT_BAD_FORMAT');
const err = new Err();

CtSthParsingFailedError

Certificate Transparency: Received a signed tree head that failed to parse.

  • Name: CtSthParsingFailedError
  • Code: -168
  • Description: CT_STH_PARSING_FAILED
  • Type: connection
const err = new chromiumNetErrors.CtSthParsingFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-168);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CT_STH_PARSING_FAILED');
const err = new Err();

CtSthIncompleteError

Certificate Transparency: Received a signed tree head whose JSON parsing was OK but was missing some of the fields.

  • Name: CtSthIncompleteError
  • Code: -169
  • Description: CT_STH_INCOMPLETE
  • Type: connection
const err = new chromiumNetErrors.CtSthIncompleteError();
// or
const Err = chromiumNetErrors.getErrorByCode(-169);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CT_STH_INCOMPLETE');
const err = new Err();

UnableToReuseConnectionForProxyAuthError

The attempt to reuse a connection to send proxy auth credentials failed before the AuthController was used to generate credentials. The caller should reuse the controller with a new connection. This error is only used internally by the network stack.

  • Name: UnableToReuseConnectionForProxyAuthError
  • Code: -170
  • Description: UNABLE_TO_REUSE_CONNECTION_FOR_PROXY_AUTH
  • Type: connection
const err = new chromiumNetErrors.UnableToReuseConnectionForProxyAuthError();
// or
const Err = chromiumNetErrors.getErrorByCode(-170);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNABLE_TO_REUSE_CONNECTION_FOR_PROXY_AUTH');
const err = new Err();

CtConsistencyProofParsingFailedError

Certificate Transparency: Failed to parse the received consistency proof.

  • Name: CtConsistencyProofParsingFailedError
  • Code: -171
  • Description: CT_CONSISTENCY_PROOF_PARSING_FAILED
  • Type: connection
const err = new chromiumNetErrors.CtConsistencyProofParsingFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-171);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CT_CONSISTENCY_PROOF_PARSING_FAILED');
const err = new Err();

SslObsoleteCipherError

The SSL server required an unsupported cipher suite that has since been removed. This error will temporarily be signaled on a fallback for one or two releases immediately following a cipher suite's removal, after which the fallback will be removed.

  • Name: SslObsoleteCipherError
  • Code: -172
  • Description: SSL_OBSOLETE_CIPHER
  • Type: connection
const err = new chromiumNetErrors.SslObsoleteCipherError();
// or
const Err = chromiumNetErrors.getErrorByCode(-172);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_OBSOLETE_CIPHER');
const err = new Err();

WsUpgradeError

When a WebSocket handshake is done successfully and the connection has been upgraded, the URLRequest is cancelled with this error code.

  • Name: WsUpgradeError
  • Code: -173
  • Description: WS_UPGRADE
  • Type: connection
const err = new chromiumNetErrors.WsUpgradeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-173);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('WS_UPGRADE');
const err = new Err();

ReadIfReadyNotImplementedError

Socket ReadIfReady support is not implemented. This error should not be user visible, because the normal Read() method is used as a fallback.

  • Name: ReadIfReadyNotImplementedError
  • Code: -174
  • Description: READ_IF_READY_NOT_IMPLEMENTED
  • Type: connection
const err = new chromiumNetErrors.ReadIfReadyNotImplementedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-174);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('READ_IF_READY_NOT_IMPLEMENTED');
const err = new Err();

NoBufferSpaceError

No socket buffer space is available.

  • Name: NoBufferSpaceError
  • Code: -176
  • Description: NO_BUFFER_SPACE
  • Type: connection
const err = new chromiumNetErrors.NoBufferSpaceError();
// or
const Err = chromiumNetErrors.getErrorByCode(-176);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NO_BUFFER_SPACE');
const err = new Err();

SslClientAuthNoCommonAlgorithmsError

There were no common signature algorithms between our client certificate private key and the server's preferences.

  • Name: SslClientAuthNoCommonAlgorithmsError
  • Code: -177
  • Description: SSL_CLIENT_AUTH_NO_COMMON_ALGORITHMS
  • Type: connection
const err = new chromiumNetErrors.SslClientAuthNoCommonAlgorithmsError();
// or
const Err = chromiumNetErrors.getErrorByCode(-177);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_CLIENT_AUTH_NO_COMMON_ALGORITHMS');
const err = new Err();

EarlyDataRejectedError

TLS 1.3 early data was rejected by the server. This will be received before any data is returned from the socket. The request should be retried with early data disabled.

  • Name: EarlyDataRejectedError
  • Code: -178
  • Description: EARLY_DATA_REJECTED
  • Type: connection
const err = new chromiumNetErrors.EarlyDataRejectedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-178);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('EARLY_DATA_REJECTED');
const err = new Err();

WrongVersionOnEarlyDataError

TLS 1.3 early data was offered, but the server responded with TLS 1.2 or earlier. This is an internal error code to account for a backwards-compatibility issue with early data and TLS 1.2. It will be received before any data is returned from the socket. The request should be retried with early data disabled.

See https://tools.ietf.org/html/rfc8446#appendix-D.3 for details.

  • Name: WrongVersionOnEarlyDataError
  • Code: -179
  • Description: WRONG_VERSION_ON_EARLY_DATA
  • Type: connection
const err = new chromiumNetErrors.WrongVersionOnEarlyDataError();
// or
const Err = chromiumNetErrors.getErrorByCode(-179);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('WRONG_VERSION_ON_EARLY_DATA');
const err = new Err();

Tls13DowngradeDetectedError

TLS 1.3 was enabled, but a lower version was negotiated and the server returned a value indicating it supported TLS 1.3. This is part of a security check in TLS 1.3, but it may also indicate the user is behind a buggy TLS-terminating proxy which implemented TLS 1.2 incorrectly. (See https://crbug.com/boringssl/226.)

  • Name: Tls13DowngradeDetectedError
  • Code: -180
  • Description: TLS13_DOWNGRADE_DETECTED
  • Type: connection
const err = new chromiumNetErrors.Tls13DowngradeDetectedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-180);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('TLS13_DOWNGRADE_DETECTED');
const err = new Err();

SslKeyUsageIncompatibleError

The server's certificate has a keyUsage extension incompatible with the negotiated TLS key exchange method.

  • Name: SslKeyUsageIncompatibleError
  • Code: -181
  • Description: SSL_KEY_USAGE_INCOMPATIBLE
  • Type: connection
const err = new chromiumNetErrors.SslKeyUsageIncompatibleError();
// or
const Err = chromiumNetErrors.getErrorByCode(-181);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_KEY_USAGE_INCOMPATIBLE');
const err = new Err();

CertCommonNameInvalidError

The server responded with a certificate whose common name did not match the host name. This could mean:

An attacker has redirected our traffic to their server and is presenting a certificate for which they know the private key.

The server is misconfigured and responding with the wrong cert.

The user is on a wireless network and is being redirected to the network's login page.

The OS has used a DNS search suffix and the server doesn't have a certificate for the abbreviated name in the address bar.

  • Name: CertCommonNameInvalidError
  • Code: -200
  • Description: CERT_COMMON_NAME_INVALID
  • Type: certificate
const err = new chromiumNetErrors.CertCommonNameInvalidError();
// or
const Err = chromiumNetErrors.getErrorByCode(-200);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_COMMON_NAME_INVALID');
const err = new Err();

CertDateInvalidError

The server responded with a certificate that, by our clock, appears to either not yet be valid or to have expired. This could mean:

An attacker is presenting an old certificate for which they have managed to obtain the private key.

The server is misconfigured and is not presenting a valid cert.

Our clock is wrong.

  • Name: CertDateInvalidError
  • Code: -201
  • Description: CERT_DATE_INVALID
  • Type: certificate
const err = new chromiumNetErrors.CertDateInvalidError();
// or
const Err = chromiumNetErrors.getErrorByCode(-201);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_DATE_INVALID');
const err = new Err();

CertAuthorityInvalidError

The server responded with a certificate that is signed by an authority we don't trust. The could mean:

An attacker has substituted the real certificate for a cert that contains their public key and is signed by their cousin.

The server operator has a legitimate certificate from a CA we don't know about, but should trust.

The server is presenting a self-signed certificate, providing no defense against active attackers (but foiling passive attackers).

  • Name: CertAuthorityInvalidError
  • Code: -202
  • Description: CERT_AUTHORITY_INVALID
  • Type: certificate
const err = new chromiumNetErrors.CertAuthorityInvalidError();
// or
const Err = chromiumNetErrors.getErrorByCode(-202);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_AUTHORITY_INVALID');
const err = new Err();

CertContainsErrorsError

The server responded with a certificate that contains errors. This error is not recoverable.

MSDN describes this error as follows: "The SSL certificate contains errors." NOTE: It's unclear how this differs from ERR_CERT_INVALID. For consistency, use that code instead of this one from now on.

  • Name: CertContainsErrorsError
  • Code: -203
  • Description: CERT_CONTAINS_ERRORS
  • Type: certificate
const err = new chromiumNetErrors.CertContainsErrorsError();
// or
const Err = chromiumNetErrors.getErrorByCode(-203);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_CONTAINS_ERRORS');
const err = new Err();

CertNoRevocationMechanismError

The certificate has no mechanism for determining if it is revoked. In effect, this certificate cannot be revoked.

  • Name: CertNoRevocationMechanismError
  • Code: -204
  • Description: CERT_NO_REVOCATION_MECHANISM
  • Type: certificate
const err = new chromiumNetErrors.CertNoRevocationMechanismError();
// or
const Err = chromiumNetErrors.getErrorByCode(-204);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_NO_REVOCATION_MECHANISM');
const err = new Err();

CertUnableToCheckRevocationError

Revocation information for the security certificate for this site is not available. This could mean:

An attacker has compromised the private key in the certificate and is blocking our attempt to find out that the cert was revoked.

The certificate is unrevoked, but the revocation server is busy or unavailable.

  • Name: CertUnableToCheckRevocationError
  • Code: -205
  • Description: CERT_UNABLE_TO_CHECK_REVOCATION
  • Type: certificate
const err = new chromiumNetErrors.CertUnableToCheckRevocationError();
// or
const Err = chromiumNetErrors.getErrorByCode(-205);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_UNABLE_TO_CHECK_REVOCATION');
const err = new Err();

CertRevokedError

The server responded with a certificate has been revoked. We have the capability to ignore this error, but it is probably not the thing to do.

  • Name: CertRevokedError
  • Code: -206
  • Description: CERT_REVOKED
  • Type: certificate
const err = new chromiumNetErrors.CertRevokedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-206);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_REVOKED');
const err = new Err();

CertInvalidError

The server responded with a certificate that is invalid. This error is not recoverable.

MSDN describes this error as follows: "The SSL certificate is invalid."

  • Name: CertInvalidError
  • Code: -207
  • Description: CERT_INVALID
  • Type: certificate
const err = new chromiumNetErrors.CertInvalidError();
// or
const Err = chromiumNetErrors.getErrorByCode(-207);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_INVALID');
const err = new Err();

CertWeakSignatureAlgorithmError

The server responded with a certificate that is signed using a weak signature algorithm.

  • Name: CertWeakSignatureAlgorithmError
  • Code: -208
  • Description: CERT_WEAK_SIGNATURE_ALGORITHM
  • Type: certificate
const err = new chromiumNetErrors.CertWeakSignatureAlgorithmError();
// or
const Err = chromiumNetErrors.getErrorByCode(-208);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_WEAK_SIGNATURE_ALGORITHM');
const err = new Err();

CertNonUniqueNameError

The host name specified in the certificate is not unique.

  • Name: CertNonUniqueNameError
  • Code: -210
  • Description: CERT_NON_UNIQUE_NAME
  • Type: certificate
const err = new chromiumNetErrors.CertNonUniqueNameError();
// or
const Err = chromiumNetErrors.getErrorByCode(-210);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_NON_UNIQUE_NAME');
const err = new Err();

CertWeakKeyError

The server responded with a certificate that contains a weak key (e.g. a too-small RSA key).

  • Name: CertWeakKeyError
  • Code: -211
  • Description: CERT_WEAK_KEY
  • Type: certificate
const err = new chromiumNetErrors.CertWeakKeyError();
// or
const Err = chromiumNetErrors.getErrorByCode(-211);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_WEAK_KEY');
const err = new Err();

CertNameConstraintViolationError

The certificate claimed DNS names that are in violation of name constraints.

  • Name: CertNameConstraintViolationError
  • Code: -212
  • Description: CERT_NAME_CONSTRAINT_VIOLATION
  • Type: certificate
const err = new chromiumNetErrors.CertNameConstraintViolationError();
// or
const Err = chromiumNetErrors.getErrorByCode(-212);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_NAME_CONSTRAINT_VIOLATION');
const err = new Err();

CertValidityTooLongError

The certificate's validity period is too long.

  • Name: CertValidityTooLongError
  • Code: -213
  • Description: CERT_VALIDITY_TOO_LONG
  • Type: certificate
const err = new chromiumNetErrors.CertValidityTooLongError();
// or
const Err = chromiumNetErrors.getErrorByCode(-213);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_VALIDITY_TOO_LONG');
const err = new Err();

CertificateTransparencyRequiredError

Certificate Transparency was required for this connection, but the server did not provide CT information that complied with the policy.

  • Name: CertificateTransparencyRequiredError
  • Code: -214
  • Description: CERTIFICATE_TRANSPARENCY_REQUIRED
  • Type: certificate
const err = new chromiumNetErrors.CertificateTransparencyRequiredError();
// or
const Err = chromiumNetErrors.getErrorByCode(-214);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERTIFICATE_TRANSPARENCY_REQUIRED');
const err = new Err();

CertSymantecLegacyError

The certificate chained to a legacy Symantec root that is no longer trusted. https://g.co/chrome/symantecpkicerts

  • Name: CertSymantecLegacyError
  • Code: -215
  • Description: CERT_SYMANTEC_LEGACY
  • Type: certificate
const err = new chromiumNetErrors.CertSymantecLegacyError();
// or
const Err = chromiumNetErrors.getErrorByCode(-215);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_SYMANTEC_LEGACY');
const err = new Err();

CertKnownInterceptionBlockedError

The certificate is known to be used for interception by an entity other the device owner.

  • Name: CertKnownInterceptionBlockedError
  • Code: -217
  • Description: CERT_KNOWN_INTERCEPTION_BLOCKED
  • Type: certificate
const err = new chromiumNetErrors.CertKnownInterceptionBlockedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-217);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_KNOWN_INTERCEPTION_BLOCKED');
const err = new Err();

SslObsoleteVersionError

The connection uses an obsolete version of SSL/TLS.

  • Name: SslObsoleteVersionError
  • Code: -218
  • Description: SSL_OBSOLETE_VERSION
  • Type: certificate
const err = new chromiumNetErrors.SslObsoleteVersionError();
// or
const Err = chromiumNetErrors.getErrorByCode(-218);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_OBSOLETE_VERSION');
const err = new Err();

CertEndError

The value immediately past the last certificate error code.

  • Name: CertEndError
  • Code: -219
  • Description: CERT_END
  • Type: certificate
const err = new chromiumNetErrors.CertEndError();
// or
const Err = chromiumNetErrors.getErrorByCode(-219);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_END');
const err = new Err();

InvalidUrlError

The URL is invalid.

  • Name: InvalidUrlError
  • Code: -300
  • Description: INVALID_URL
  • Type: http
const err = new chromiumNetErrors.InvalidUrlError();
// or
const Err = chromiumNetErrors.getErrorByCode(-300);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_URL');
const err = new Err();

DisallowedUrlSchemeError

The scheme of the URL is disallowed.

  • Name: DisallowedUrlSchemeError
  • Code: -301
  • Description: DISALLOWED_URL_SCHEME
  • Type: http
const err = new chromiumNetErrors.DisallowedUrlSchemeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-301);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DISALLOWED_URL_SCHEME');
const err = new Err();

UnknownUrlSchemeError

The scheme of the URL is unknown.

  • Name: UnknownUrlSchemeError
  • Code: -302
  • Description: UNKNOWN_URL_SCHEME
  • Type: http
const err = new chromiumNetErrors.UnknownUrlSchemeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-302);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNKNOWN_URL_SCHEME');
const err = new Err();

InvalidRedirectError

Attempting to load an URL resulted in a redirect to an invalid URL.

  • Name: InvalidRedirectError
  • Code: -303
  • Description: INVALID_REDIRECT
  • Type: http
const err = new chromiumNetErrors.InvalidRedirectError();
// or
const Err = chromiumNetErrors.getErrorByCode(-303);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_REDIRECT');
const err = new Err();

TooManyRedirectsError

Attempting to load an URL resulted in too many redirects.

  • Name: TooManyRedirectsError
  • Code: -310
  • Description: TOO_MANY_REDIRECTS
  • Type: http
const err = new chromiumNetErrors.TooManyRedirectsError();
// or
const Err = chromiumNetErrors.getErrorByCode(-310);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('TOO_MANY_REDIRECTS');
const err = new Err();

UnsafeRedirectError

Attempting to load an URL resulted in an unsafe redirect (e.g., a redirect to file:// is considered unsafe).

  • Name: UnsafeRedirectError
  • Code: -311
  • Description: UNSAFE_REDIRECT
  • Type: http
const err = new chromiumNetErrors.UnsafeRedirectError();
// or
const Err = chromiumNetErrors.getErrorByCode(-311);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNSAFE_REDIRECT');
const err = new Err();

UnsafePortError

Attempting to load an URL with an unsafe port number. These are port numbers that correspond to services, which are not robust to spurious input that may be constructed as a result of an allowed web construct (e.g., HTTP looks a lot like SMTP, so form submission to port 25 is denied).

  • Name: UnsafePortError
  • Code: -312
  • Description: UNSAFE_PORT
  • Type: http
const err = new chromiumNetErrors.UnsafePortError();
// or
const Err = chromiumNetErrors.getErrorByCode(-312);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNSAFE_PORT');
const err = new Err();

InvalidResponseError

The server's response was invalid.

  • Name: InvalidResponseError
  • Code: -320
  • Description: INVALID_RESPONSE
  • Type: http
const err = new chromiumNetErrors.InvalidResponseError();
// or
const Err = chromiumNetErrors.getErrorByCode(-320);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_RESPONSE');
const err = new Err();

InvalidChunkedEncodingError

Error in chunked transfer encoding.

  • Name: InvalidChunkedEncodingError
  • Code: -321
  • Description: INVALID_CHUNKED_ENCODING
  • Type: http
const err = new chromiumNetErrors.InvalidChunkedEncodingError();
// or
const Err = chromiumNetErrors.getErrorByCode(-321);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_CHUNKED_ENCODING');
const err = new Err();

MethodNotSupportedError

The server did not support the request method.

  • Name: MethodNotSupportedError
  • Code: -322
  • Description: METHOD_NOT_SUPPORTED
  • Type: http
const err = new chromiumNetErrors.MethodNotSupportedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-322);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('METHOD_NOT_SUPPORTED');
const err = new Err();

UnexpectedProxyAuthError

The response was 407 (Proxy Authentication Required), yet we did not send the request to a proxy.

  • Name: UnexpectedProxyAuthError
  • Code: -323
  • Description: UNEXPECTED_PROXY_AUTH
  • Type: http
const err = new chromiumNetErrors.UnexpectedProxyAuthError();
// or
const Err = chromiumNetErrors.getErrorByCode(-323);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNEXPECTED_PROXY_AUTH');
const err = new Err();

EmptyResponseError

The server closed the connection without sending any data.

  • Name: EmptyResponseError
  • Code: -324
  • Description: EMPTY_RESPONSE
  • Type: http
const err = new chromiumNetErrors.EmptyResponseError();
// or
const Err = chromiumNetErrors.getErrorByCode(-324);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('EMPTY_RESPONSE');
const err = new Err();

ResponseHeadersTooBigError

The headers section of the response is too large.

  • Name: ResponseHeadersTooBigError
  • Code: -325
  • Description: RESPONSE_HEADERS_TOO_BIG
  • Type: http
const err = new chromiumNetErrors.ResponseHeadersTooBigError();
// or
const Err = chromiumNetErrors.getErrorByCode(-325);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('RESPONSE_HEADERS_TOO_BIG');
const err = new Err();

PacScriptFailedError

The evaluation of the PAC script failed.

  • Name: PacScriptFailedError
  • Code: -327
  • Description: PAC_SCRIPT_FAILED
  • Type: http
const err = new chromiumNetErrors.PacScriptFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-327);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PAC_SCRIPT_FAILED');
const err = new Err();

RequestRangeNotSatisfiableError

The response was 416 (Requested range not satisfiable) and the server cannot satisfy the range requested.

  • Name: RequestRangeNotSatisfiableError
  • Code: -328
  • Description: REQUEST_RANGE_NOT_SATISFIABLE
  • Type: http
const err = new chromiumNetErrors.RequestRangeNotSatisfiableError();
// or
const Err = chromiumNetErrors.getErrorByCode(-328);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('REQUEST_RANGE_NOT_SATISFIABLE');
const err = new Err();

MalformedIdentityError

The identity used for authentication is invalid.

  • Name: MalformedIdentityError
  • Code: -329
  • Description: MALFORMED_IDENTITY
  • Type: http
const err = new chromiumNetErrors.MalformedIdentityError();
// or
const Err = chromiumNetErrors.getErrorByCode(-329);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('MALFORMED_IDENTITY');
const err = new Err();

ContentDecodingFailedError

Content decoding of the response body failed.

  • Name: ContentDecodingFailedError
  • Code: -330
  • Description: CONTENT_DECODING_FAILED
  • Type: http
const err = new chromiumNetErrors.ContentDecodingFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-330);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONTENT_DECODING_FAILED');
const err = new Err();

NetworkIoSuspendedError

An operation could not be completed because all network IO is suspended.

  • Name: NetworkIoSuspendedError
  • Code: -331
  • Description: NETWORK_IO_SUSPENDED
  • Type: http
const err = new chromiumNetErrors.NetworkIoSuspendedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-331);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NETWORK_IO_SUSPENDED');
const err = new Err();

SynReplyNotReceivedError

FLIP data received without receiving a SYN_REPLY on the stream.

  • Name: SynReplyNotReceivedError
  • Code: -332
  • Description: SYN_REPLY_NOT_RECEIVED
  • Type: http
const err = new chromiumNetErrors.SynReplyNotReceivedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-332);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SYN_REPLY_NOT_RECEIVED');
const err = new Err();

EncodingConversionFailedError

Converting the response to target encoding failed.

  • Name: EncodingConversionFailedError
  • Code: -333
  • Description: ENCODING_CONVERSION_FAILED
  • Type: http
const err = new chromiumNetErrors.EncodingConversionFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-333);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ENCODING_CONVERSION_FAILED');
const err = new Err();

UnrecognizedFtpDirectoryListingFormatError

The server sent an FTP directory listing in a format we do not understand.

  • Name: UnrecognizedFtpDirectoryListingFormatError
  • Code: -334
  • Description: UNRECOGNIZED_FTP_DIRECTORY_LISTING_FORMAT
  • Type: http
const err = new chromiumNetErrors.UnrecognizedFtpDirectoryListingFormatError();
// or
const Err = chromiumNetErrors.getErrorByCode(-334);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNRECOGNIZED_FTP_DIRECTORY_LISTING_FORMAT');
const err = new Err();

NoSupportedProxiesError

There are no supported proxies in the provided list.

  • Name: NoSupportedProxiesError
  • Code: -336
  • Description: NO_SUPPORTED_PROXIES
  • Type: http
const err = new chromiumNetErrors.NoSupportedProxiesError();
// or
const Err = chromiumNetErrors.getErrorByCode(-336);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NO_SUPPORTED_PROXIES');
const err = new Err();

Http2ProtocolError

There is an HTTP/2 protocol error.

  • Name: Http2ProtocolError
  • Code: -337
  • Description: HTTP2_PROTOCOL_ERROR
  • Type: http
const err = new chromiumNetErrors.Http2ProtocolError();
// or
const Err = chromiumNetErrors.getErrorByCode(-337);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_PROTOCOL_ERROR');
const err = new Err();

InvalidAuthCredentialsError

Credentials could not be established during HTTP Authentication.

  • Name: InvalidAuthCredentialsError
  • Code: -338
  • Description: INVALID_AUTH_CREDENTIALS
  • Type: http
const err = new chromiumNetErrors.InvalidAuthCredentialsError();
// or
const Err = chromiumNetErrors.getErrorByCode(-338);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_AUTH_CREDENTIALS');
const err = new Err();

UnsupportedAuthSchemeError

An HTTP Authentication scheme was tried which is not supported on this machine.

  • Name: UnsupportedAuthSchemeError
  • Code: -339
  • Description: UNSUPPORTED_AUTH_SCHEME
  • Type: http
const err = new chromiumNetErrors.UnsupportedAuthSchemeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-339);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNSUPPORTED_AUTH_SCHEME');
const err = new Err();

EncodingDetectionFailedError

Detecting the encoding of the response failed.

  • Name: EncodingDetectionFailedError
  • Code: -340
  • Description: ENCODING_DETECTION_FAILED
  • Type: http
const err = new chromiumNetErrors.EncodingDetectionFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-340);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ENCODING_DETECTION_FAILED');
const err = new Err();

MissingAuthCredentialsError

(GSSAPI) No Kerberos credentials were available during HTTP Authentication.

  • Name: MissingAuthCredentialsError
  • Code: -341
  • Description: MISSING_AUTH_CREDENTIALS
  • Type: http
const err = new chromiumNetErrors.MissingAuthCredentialsError();
// or
const Err = chromiumNetErrors.getErrorByCode(-341);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('MISSING_AUTH_CREDENTIALS');
const err = new Err();

UnexpectedSecurityLibraryStatusError

An unexpected, but documented, SSPI or GSSAPI status code was returned.

  • Name: UnexpectedSecurityLibraryStatusError
  • Code: -342
  • Description: UNEXPECTED_SECURITY_LIBRARY_STATUS
  • Type: http
const err = new chromiumNetErrors.UnexpectedSecurityLibraryStatusError();
// or
const Err = chromiumNetErrors.getErrorByCode(-342);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNEXPECTED_SECURITY_LIBRARY_STATUS');
const err = new Err();

MisconfiguredAuthEnvironmentError

The environment was not set up correctly for authentication (for example, no KDC could be found or the principal is unknown.

  • Name: MisconfiguredAuthEnvironmentError
  • Code: -343
  • Description: MISCONFIGURED_AUTH_ENVIRONMENT
  • Type: http
const err = new chromiumNetErrors.MisconfiguredAuthEnvironmentError();
// or
const Err = chromiumNetErrors.getErrorByCode(-343);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('MISCONFIGURED_AUTH_ENVIRONMENT');
const err = new Err();

UndocumentedSecurityLibraryStatusError

An undocumented SSPI or GSSAPI status code was returned.

  • Name: UndocumentedSecurityLibraryStatusError
  • Code: -344
  • Description: UNDOCUMENTED_SECURITY_LIBRARY_STATUS
  • Type: http
const err = new chromiumNetErrors.UndocumentedSecurityLibraryStatusError();
// or
const Err = chromiumNetErrors.getErrorByCode(-344);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNDOCUMENTED_SECURITY_LIBRARY_STATUS');
const err = new Err();

ResponseBodyTooBigToDrainError

The HTTP response was too big to drain.

  • Name: ResponseBodyTooBigToDrainError
  • Code: -345
  • Description: RESPONSE_BODY_TOO_BIG_TO_DRAIN
  • Type: http
const err = new chromiumNetErrors.ResponseBodyTooBigToDrainError();
// or
const Err = chromiumNetErrors.getErrorByCode(-345);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('RESPONSE_BODY_TOO_BIG_TO_DRAIN');
const err = new Err();

ResponseHeadersMultipleContentLengthError

The HTTP response contained multiple distinct Content-Length headers.

  • Name: ResponseHeadersMultipleContentLengthError
  • Code: -346
  • Description: RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH
  • Type: http
const err = new chromiumNetErrors.ResponseHeadersMultipleContentLengthError();
// or
const Err = chromiumNetErrors.getErrorByCode(-346);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH');
const err = new Err();

IncompleteHttp2HeadersError

HTTP/2 headers have been received, but not all of them - status or version headers are missing, so we're expecting additional frames to complete them.

  • Name: IncompleteHttp2HeadersError
  • Code: -347
  • Description: INCOMPLETE_HTTP2_HEADERS
  • Type: http
const err = new chromiumNetErrors.IncompleteHttp2HeadersError();
// or
const Err = chromiumNetErrors.getErrorByCode(-347);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INCOMPLETE_HTTP2_HEADERS');
const err = new Err();

PacNotInDhcpError

No PAC URL configuration could be retrieved from DHCP. This can indicate either a failure to retrieve the DHCP configuration, or that there was no PAC URL configured in DHCP.

  • Name: PacNotInDhcpError
  • Code: -348
  • Description: PAC_NOT_IN_DHCP
  • Type: http
const err = new chromiumNetErrors.PacNotInDhcpError();
// or
const Err = chromiumNetErrors.getErrorByCode(-348);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PAC_NOT_IN_DHCP');
const err = new Err();

ResponseHeadersMultipleContentDispositionError

The HTTP response contained multiple Content-Disposition headers.

  • Name: ResponseHeadersMultipleContentDispositionError
  • Code: -349
  • Description: RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION
  • Type: http
const err = new chromiumNetErrors.ResponseHeadersMultipleContentDispositionError();
// or
const Err = chromiumNetErrors.getErrorByCode(-349);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION');
const err = new Err();

ResponseHeadersMultipleLocationError

The HTTP response contained multiple Location headers.

  • Name: ResponseHeadersMultipleLocationError
  • Code: -350
  • Description: RESPONSE_HEADERS_MULTIPLE_LOCATION
  • Type: http
const err = new chromiumNetErrors.ResponseHeadersMultipleLocationError();
// or
const Err = chromiumNetErrors.getErrorByCode(-350);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('RESPONSE_HEADERS_MULTIPLE_LOCATION');
const err = new Err();

Http2ServerRefusedStreamError

HTTP/2 server refused the request without processing, and sent either a GOAWAY frame with error code NO_ERROR and Last-Stream-ID lower than the stream id corresponding to the request indicating that this request has not been processed yet, or a RST_STREAM frame with error code REFUSED_STREAM. Client MAY retry (on a different connection). See RFC7540 Section 8.1.4.

  • Name: Http2ServerRefusedStreamError
  • Code: -351
  • Description: HTTP2_SERVER_REFUSED_STREAM
  • Type: http
const err = new chromiumNetErrors.Http2ServerRefusedStreamError();
// or
const Err = chromiumNetErrors.getErrorByCode(-351);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_SERVER_REFUSED_STREAM');
const err = new Err();

Http2PingFailedError

HTTP/2 server didn't respond to the PING message.

  • Name: Http2PingFailedError
  • Code: -352
  • Description: HTTP2_PING_FAILED
  • Type: http
const err = new chromiumNetErrors.Http2PingFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-352);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_PING_FAILED');
const err = new Err();

ContentLengthMismatchError

The HTTP response body transferred fewer bytes than were advertised by the Content-Length header when the connection is closed.

  • Name: ContentLengthMismatchError
  • Code: -354
  • Description: CONTENT_LENGTH_MISMATCH
  • Type: http
const err = new chromiumNetErrors.ContentLengthMismatchError();
// or
const Err = chromiumNetErrors.getErrorByCode(-354);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONTENT_LENGTH_MISMATCH');
const err = new Err();

IncompleteChunkedEncodingError

The HTTP response body is transferred with Chunked-Encoding, but the terminating zero-length chunk was never sent when the connection is closed.

  • Name: IncompleteChunkedEncodingError
  • Code: -355
  • Description: INCOMPLETE_CHUNKED_ENCODING
  • Type: http
const err = new chromiumNetErrors.IncompleteChunkedEncodingError();
// or
const Err = chromiumNetErrors.getErrorByCode(-355);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INCOMPLETE_CHUNKED_ENCODING');
const err = new Err();

QuicProtocolError

There is a QUIC protocol error.

  • Name: QuicProtocolError
  • Code: -356
  • Description: QUIC_PROTOCOL_ERROR
  • Type: http
const err = new chromiumNetErrors.QuicProtocolError();
// or
const Err = chromiumNetErrors.getErrorByCode(-356);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('QUIC_PROTOCOL_ERROR');
const err = new Err();

ResponseHeadersTruncatedError

The HTTP headers were truncated by an EOF.

  • Name: ResponseHeadersTruncatedError
  • Code: -357
  • Description: RESPONSE_HEADERS_TRUNCATED
  • Type: http
const err = new chromiumNetErrors.ResponseHeadersTruncatedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-357);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('RESPONSE_HEADERS_TRUNCATED');
const err = new Err();

QuicHandshakeFailedError

The QUIC crytpo handshake failed. This means that the server was unable to read any requests sent, so they may be resent.

  • Name: QuicHandshakeFailedError
  • Code: -358
  • Description: QUIC_HANDSHAKE_FAILED
  • Type: http
const err = new chromiumNetErrors.QuicHandshakeFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-358);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('QUIC_HANDSHAKE_FAILED');
const err = new Err();

Http2InadequateTransportSecurityError

Transport security is inadequate for the HTTP/2 version.

  • Name: Http2InadequateTransportSecurityError
  • Code: -360
  • Description: HTTP2_INADEQUATE_TRANSPORT_SECURITY
  • Type: http
const err = new chromiumNetErrors.Http2InadequateTransportSecurityError();
// or
const Err = chromiumNetErrors.getErrorByCode(-360);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_INADEQUATE_TRANSPORT_SECURITY');
const err = new Err();

Http2FlowControlError

The peer violated HTTP/2 flow control.

  • Name: Http2FlowControlError
  • Code: -361
  • Description: HTTP2_FLOW_CONTROL_ERROR
  • Type: http
const err = new chromiumNetErrors.Http2FlowControlError();
// or
const Err = chromiumNetErrors.getErrorByCode(-361);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_FLOW_CONTROL_ERROR');
const err = new Err();

Http2FrameSizeError

The peer sent an improperly sized HTTP/2 frame.

  • Name: Http2FrameSizeError
  • Code: -362
  • Description: HTTP2_FRAME_SIZE_ERROR
  • Type: http
const err = new chromiumNetErrors.Http2FrameSizeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-362);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_FRAME_SIZE_ERROR');
const err = new Err();

Http2CompressionError

Decoding or encoding of compressed HTTP/2 headers failed.

  • Name: Http2CompressionError
  • Code: -363
  • Description: HTTP2_COMPRESSION_ERROR
  • Type: http
const err = new chromiumNetErrors.Http2CompressionError();
// or
const Err = chromiumNetErrors.getErrorByCode(-363);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_COMPRESSION_ERROR');
const err = new Err();

ProxyAuthRequestedWithNoConnectionError

Proxy Auth Requested without a valid Client Socket Handle.

  • Name: ProxyAuthRequestedWithNoConnectionError
  • Code: -364
  • Description: PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION
  • Type: http
const err = new chromiumNetErrors.ProxyAuthRequestedWithNoConnectionError();
// or
const Err = chromiumNetErrors.getErrorByCode(-364);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION');
const err = new Err();

Http_1_1RequiredError

HTTP_1_1_REQUIRED error code received on HTTP/2 session.

  • Name: Http_1_1RequiredError
  • Code: -365
  • Description: HTTP_1_1_REQUIRED
  • Type: http
const err = new chromiumNetErrors.Http_1_1RequiredError();
// or
const Err = chromiumNetErrors.getErrorByCode(-365);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP_1_1_REQUIRED');
const err = new Err();

ProxyHttp_1_1RequiredError

HTTP_1_1_REQUIRED error code received on HTTP/2 session to proxy.

  • Name: ProxyHttp_1_1RequiredError
  • Code: -366
  • Description: PROXY_HTTP_1_1_REQUIRED
  • Type: http
const err = new chromiumNetErrors.ProxyHttp_1_1RequiredError();
// or
const Err = chromiumNetErrors.getErrorByCode(-366);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PROXY_HTTP_1_1_REQUIRED');
const err = new Err();

PacScriptTerminatedError

The PAC script terminated fatally and must be reloaded.

  • Name: PacScriptTerminatedError
  • Code: -367
  • Description: PAC_SCRIPT_TERMINATED
  • Type: http
const err = new chromiumNetErrors.PacScriptTerminatedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-367);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PAC_SCRIPT_TERMINATED');
const err = new Err();

InvalidHttpResponseError

The server was expected to return an HTTP/1.x response, but did not. Rather than treat it as HTTP/0.9, this error is returned.

  • Name: InvalidHttpResponseError
  • Code: -370
  • Description: INVALID_HTTP_RESPONSE
  • Type: http
const err = new chromiumNetErrors.InvalidHttpResponseError();
// or
const Err = chromiumNetErrors.getErrorByCode(-370);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_HTTP_RESPONSE');
const err = new Err();

ContentDecodingInitFailedError

Initializing content decoding failed.

  • Name: ContentDecodingInitFailedError
  • Code: -371
  • Description: CONTENT_DECODING_INIT_FAILED
  • Type: http
const err = new chromiumNetErrors.ContentDecodingInitFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-371);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONTENT_DECODING_INIT_FAILED');
const err = new Err();

Http2RstStreamNoErrorReceivedError

Received HTTP/2 RST_STREAM frame with NO_ERROR error code. This error should be handled internally by HTTP/2 code, and should not make it above the SpdyStream layer.

  • Name: Http2RstStreamNoErrorReceivedError
  • Code: -372
  • Description: HTTP2_RST_STREAM_NO_ERROR_RECEIVED
  • Type: http
const err = new chromiumNetErrors.Http2RstStreamNoErrorReceivedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-372);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_RST_STREAM_NO_ERROR_RECEIVED');
const err = new Err();

Http2PushedStreamNotAvailableError

The pushed stream claimed by the request is no longer available.

  • Name: Http2PushedStreamNotAvailableError
  • Code: -373
  • Description: HTTP2_PUSHED_STREAM_NOT_AVAILABLE
  • Type: http
const err = new chromiumNetErrors.Http2PushedStreamNotAvailableError();
// or
const Err = chromiumNetErrors.getErrorByCode(-373);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_PUSHED_STREAM_NOT_AVAILABLE');
const err = new Err();

Http2ClaimedPushedStreamResetByServerError

A pushed stream was claimed and later reset by the server. When this happens, the request should be retried.

  • Name: Http2ClaimedPushedStreamResetByServerError
  • Code: -374
  • Description: HTTP2_CLAIMED_PUSHED_STREAM_RESET_BY_SERVER
  • Type: http
const err = new chromiumNetErrors.Http2ClaimedPushedStreamResetByServerError();
// or
const Err = chromiumNetErrors.getErrorByCode(-374);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_CLAIMED_PUSHED_STREAM_RESET_BY_SERVER');
const err = new Err();

TooManyRetriesError

An HTTP transaction was retried too many times due for authentication or invalid certificates. This may be due to a bug in the net stack that would otherwise infinite loop, or if the server or proxy continually requests fresh credentials or presents a fresh invalid certificate.

  • Name: TooManyRetriesError
  • Code: -375
  • Description: TOO_MANY_RETRIES
  • Type: http
const err = new chromiumNetErrors.TooManyRetriesError();
// or
const Err = chromiumNetErrors.getErrorByCode(-375);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('TOO_MANY_RETRIES');
const err = new Err();

Http2StreamClosedError

Received an HTTP/2 frame on a closed stream.

  • Name: Http2StreamClosedError
  • Code: -376
  • Description: HTTP2_STREAM_CLOSED
  • Type: http
const err = new chromiumNetErrors.Http2StreamClosedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-376);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_STREAM_CLOSED');
const err = new Err();

Http2ClientRefusedStreamError

Client is refusing an HTTP/2 stream.

  • Name: Http2ClientRefusedStreamError
  • Code: -377
  • Description: HTTP2_CLIENT_REFUSED_STREAM
  • Type: http
const err = new chromiumNetErrors.Http2ClientRefusedStreamError();
// or
const Err = chromiumNetErrors.getErrorByCode(-377);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_CLIENT_REFUSED_STREAM');
const err = new Err();

Http2PushedResponseDoesNotMatchError

A pushed HTTP/2 stream was claimed by a request based on matching URL and request headers, but the pushed response headers do not match the request.

  • Name: Http2PushedResponseDoesNotMatchError
  • Code: -378
  • Description: HTTP2_PUSHED_RESPONSE_DOES_NOT_MATCH
  • Type: http
const err = new chromiumNetErrors.Http2PushedResponseDoesNotMatchError();
// or
const Err = chromiumNetErrors.getErrorByCode(-378);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_PUSHED_RESPONSE_DOES_NOT_MATCH');
const err = new Err();

HttpResponseCodeFailureError

The server returned a non-2xx HTTP response code.

Not that this error is only used by certain APIs that interpret the HTTP response itself. URLRequest for instance just passes most non-2xx response back as success.

  • Name: HttpResponseCodeFailureError
  • Code: -379
  • Description: HTTP_RESPONSE_CODE_FAILURE
  • Type: http
const err = new chromiumNetErrors.HttpResponseCodeFailureError();
// or
const Err = chromiumNetErrors.getErrorByCode(-379);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP_RESPONSE_CODE_FAILURE');
const err = new Err();

QuicCertRootNotKnownError

The certificate presented on a QUIC connection does not chain to a known root and the origin connected to is not on a list of domains where unknown roots are allowed.

  • Name: QuicCertRootNotKnownError
  • Code: -380
  • Description: QUIC_CERT_ROOT_NOT_KNOWN
  • Type: http
const err = new chromiumNetErrors.QuicCertRootNotKnownError();
// or
const Err = chromiumNetErrors.getErrorByCode(-380);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('QUIC_CERT_ROOT_NOT_KNOWN');
const err = new Err();

QuicGoawayRequestCanBeRetriedError

A GOAWAY frame has been received indicating that the request has not been processed and is therefore safe to retry on a different connection.

  • Name: QuicGoawayRequestCanBeRetriedError
  • Code: -381
  • Description: QUIC_GOAWAY_REQUEST_CAN_BE_RETRIED
  • Type: http
const err = new chromiumNetErrors.QuicGoawayRequestCanBeRetriedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-381);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('QUIC_GOAWAY_REQUEST_CAN_BE_RETRIED');
const err = new Err();

CacheMissError

The cache does not have the requested entry.

  • Name: CacheMissError
  • Code: -400
  • Description: CACHE_MISS
  • Type: cache
const err = new chromiumNetErrors.CacheMissError();
// or
const Err = chromiumNetErrors.getErrorByCode(-400);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_MISS');
const err = new Err();

CacheReadFailureError

Unable to read from the disk cache.

  • Name: CacheReadFailureError
  • Code: -401
  • Description: CACHE_READ_FAILURE
  • Type: cache
const err = new chromiumNetErrors.CacheReadFailureError();
// or
const Err = chromiumNetErrors.getErrorByCode(-401);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_READ_FAILURE');
const err = new Err();

CacheWriteFailureError

Unable to write to the disk cache.

  • Name: CacheWriteFailureError
  • Code: -402
  • Description: CACHE_WRITE_FAILURE
  • Type: cache
const err = new chromiumNetErrors.CacheWriteFailureError();
// or
const Err = chromiumNetErrors.getErrorByCode(-402);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_WRITE_FAILURE');
const err = new Err();

CacheOperationNotSupportedError

The operation is not supported for this entry.

  • Name: CacheOperationNotSupportedError
  • Code: -403
  • Description: CACHE_OPERATION_NOT_SUPPORTED
  • Type: cache
const err = new chromiumNetErrors.CacheOperationNotSupportedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-403);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_OPERATION_NOT_SUPPORTED');
const err = new Err();

CacheOpenFailureError

The disk cache is unable to open this entry.

  • Name: CacheOpenFailureError
  • Code: -404
  • Description: CACHE_OPEN_FAILURE
  • Type: cache
const err = new chromiumNetErrors.CacheOpenFailureError();
// or
const Err = chromiumNetErrors.getErrorByCode(-404);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_OPEN_FAILURE');
const err = new Err();

CacheCreateFailureError

The disk cache is unable to create this entry.

  • Name: CacheCreateFailureError
  • Code: -405
  • Description: CACHE_CREATE_FAILURE
  • Type: cache
const err = new chromiumNetErrors.CacheCreateFailureError();
// or
const Err = chromiumNetErrors.getErrorByCode(-405);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_CREATE_FAILURE');
const err = new Err();

CacheRaceError

Multiple transactions are racing to create disk cache entries. This is an internal error returned from the HttpCache to the HttpCacheTransaction that tells the transaction to restart the entry-creation logic because the state of the cache has changed.

  • Name: CacheRaceError
  • Code: -406
  • Description: CACHE_RACE
  • Type: cache
const err = new chromiumNetErrors.CacheRaceError();
// or
const Err = chromiumNetErrors.getErrorByCode(-406);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_RACE');
const err = new Err();

CacheChecksumReadFailureError

The cache was unable to read a checksum record on an entry. This can be returned from attempts to read from the cache. It is an internal error, returned by the SimpleCache backend, but not by any URLRequest methods or members.

  • Name: CacheChecksumReadFailureError
  • Code: -407
  • Description: CACHE_CHECKSUM_READ_FAILURE
  • Type: cache
const err = new chromiumNetErrors.CacheChecksumReadFailureError();
// or
const Err = chromiumNetErrors.getErrorByCode(-407);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_CHECKSUM_READ_FAILURE');
const err = new Err();

CacheChecksumMismatchError

The cache found an entry with an invalid checksum. This can be returned from attempts to read from the cache. It is an internal error, returned by the SimpleCache backend, but not by any URLRequest methods or members.

  • Name: CacheChecksumMismatchError
  • Code: -408
  • Description: CACHE_CHECKSUM_MISMATCH
  • Type: cache
const err = new chromiumNetErrors.CacheChecksumMismatchError();
// or
const Err = chromiumNetErrors.getErrorByCode(-408);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_CHECKSUM_MISMATCH');
const err = new Err();

CacheLockTimeoutError

Internal error code for the HTTP cache. The cache lock timeout has fired.

  • Name: CacheLockTimeoutError
  • Code: -409
  • Description: CACHE_LOCK_TIMEOUT
  • Type: cache
const err = new chromiumNetErrors.CacheLockTimeoutError();
// or
const Err = chromiumNetErrors.getErrorByCode(-409);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_LOCK_TIMEOUT');
const err = new Err();

CacheAuthFailureAfterReadError

Received a challenge after the transaction has read some data, and the credentials aren't available. There isn't a way to get them at that point.

  • Name: CacheAuthFailureAfterReadError
  • Code: -410
  • Description: CACHE_AUTH_FAILURE_AFTER_READ
  • Type: cache
const err = new chromiumNetErrors.CacheAuthFailureAfterReadError();
// or
const Err = chromiumNetErrors.getErrorByCode(-410);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_AUTH_FAILURE_AFTER_READ');
const err = new Err();

CacheEntryNotSuitableError

Internal not-quite error code for the HTTP cache. In-memory hints suggest that the cache entry would not have been useable with the transaction's current configuration (e.g. load flags, mode, etc.)

  • Name: CacheEntryNotSuitableError
  • Code: -411
  • Description: CACHE_ENTRY_NOT_SUITABLE
  • Type: cache
const err = new chromiumNetErrors.CacheEntryNotSuitableError();
// or
const Err = chromiumNetErrors.getErrorByCode(-411);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_ENTRY_NOT_SUITABLE');
const err = new Err();

CacheDoomFailureError

The disk cache is unable to doom this entry.

  • Name: CacheDoomFailureError
  • Code: -412
  • Description: CACHE_DOOM_FAILURE
  • Type: cache
const err = new chromiumNetErrors.CacheDoomFailureError();
// or
const Err = chromiumNetErrors.getErrorByCode(-412);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_DOOM_FAILURE');
const err = new Err();

CacheOpenOrCreateFailureError

The disk cache is unable to open or create this entry.

  • Name: CacheOpenOrCreateFailureError
  • Code: -413
  • Description: CACHE_OPEN_OR_CREATE_FAILURE
  • Type: cache
const err = new chromiumNetErrors.CacheOpenOrCreateFailureError();
// or
const Err = chromiumNetErrors.getErrorByCode(-413);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_OPEN_OR_CREATE_FAILURE');
const err = new Err();

InsecureResponseError

The server's response was insecure (e.g. there was a cert error).

  • Name: InsecureResponseError
  • Code: -501
  • Description: INSECURE_RESPONSE
  • Type: unknown
const err = new chromiumNetErrors.InsecureResponseError();
// or
const Err = chromiumNetErrors.getErrorByCode(-501);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INSECURE_RESPONSE');
const err = new Err();

NoPrivateKeyForCertError

An attempt to import a client certificate failed, as the user's key database lacked a corresponding private key.

  • Name: NoPrivateKeyForCertError
  • Code: -502
  • Description: NO_PRIVATE_KEY_FOR_CERT
  • Type: unknown
const err = new chromiumNetErrors.NoPrivateKeyForCertError();
// or
const Err = chromiumNetErrors.getErrorByCode(-502);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NO_PRIVATE_KEY_FOR_CERT');
const err = new Err();

AddUserCertFailedError

An error adding a certificate to the OS certificate database.

  • Name: AddUserCertFailedError
  • Code: -503
  • Description: ADD_USER_CERT_FAILED
  • Type: unknown
const err = new chromiumNetErrors.AddUserCertFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-503);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ADD_USER_CERT_FAILED');
const err = new Err();

InvalidSignedExchangeError

An error occurred while handling a signed exchange.

  • Name: InvalidSignedExchangeError
  • Code: -504
  • Description: INVALID_SIGNED_EXCHANGE
  • Type: unknown
const err = new chromiumNetErrors.InvalidSignedExchangeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-504);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_SIGNED_EXCHANGE');
const err = new Err();

InvalidWebBundleError

An error occurred while handling a Web Bundle source.

  • Name: InvalidWebBundleError
  • Code: -505
  • Description: INVALID_WEB_BUNDLE
  • Type: unknown
const err = new chromiumNetErrors.InvalidWebBundleError();
// or
const Err = chromiumNetErrors.getErrorByCode(-505);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_WEB_BUNDLE');
const err = new Err();

TrustTokenOperationFailedError

A Trust Tokens protocol operation-executing request failed for one of a number of reasons (precondition failure, internal error, bad response).

  • Name: TrustTokenOperationFailedError
  • Code: -506
  • Description: TRUST_TOKEN_OPERATION_FAILED
  • Type: unknown
const err = new chromiumNetErrors.TrustTokenOperationFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-506);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('TRUST_TOKEN_OPERATION_FAILED');
const err = new Err();

TrustTokenOperationSuccessWithoutSendingRequestError

When handling a Trust Tokens protocol operation-executing request, the system was able to execute the request's Trust Tokens operation without sending the request to its destination: for instance, the results could have been present in a local cache (for redemption) or the operation could have been diverted to a local provider (for "platform-provided" issuance).

  • Name: TrustTokenOperationSuccessWithoutSendingRequestError
  • Code: -507
  • Description: TRUST_TOKEN_OPERATION_SUCCESS_WITHOUT_SENDING_REQUEST
  • Type: unknown
const err = new chromiumNetErrors.TrustTokenOperationSuccessWithoutSendingRequestError();
// or
const Err = chromiumNetErrors.getErrorByCode(-507);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('TRUST_TOKEN_OPERATION_SUCCESS_WITHOUT_SENDING_REQUEST');
const err = new Err();

FtpFailedError

A generic error for failed FTP control connection command. If possible, please use or add a more specific error code.

  • Name: FtpFailedError
  • Code: -601
  • Description: FTP_FAILED
  • Type: ftp
const err = new chromiumNetErrors.FtpFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-601);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FTP_FAILED');
const err = new Err();

FtpServiceUnavailableError

The server cannot fulfill the request at this point. This is a temporary error. FTP response code 421.

  • Name: FtpServiceUnavailableError
  • Code: -602
  • Description: FTP_SERVICE_UNAVAILABLE
  • Type: ftp
const err = new chromiumNetErrors.FtpServiceUnavailableError();
// or
const Err = chromiumNetErrors.getErrorByCode(-602);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FTP_SERVICE_UNAVAILABLE');
const err = new Err();

FtpTransferAbortedError

The server has aborted the transfer. FTP response code 426.

  • Name: FtpTransferAbortedError
  • Code: -603
  • Description: FTP_TRANSFER_ABORTED
  • Type: ftp
const err = new chromiumNetErrors.FtpTransferAbortedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-603);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FTP_TRANSFER_ABORTED');
const err = new Err();

FtpFileBusyError

The file is busy, or some other temporary error condition on opening the file. FTP response code 450.

  • Name: FtpFileBusyError
  • Code: -604
  • Description: FTP_FILE_BUSY
  • Type: ftp
const err = new chromiumNetErrors.FtpFileBusyError();
// or
const Err = chromiumNetErrors.getErrorByCode(-604);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FTP_FILE_BUSY');
const err = new Err();

FtpSyntaxError

Server rejected our command because of syntax errors. FTP response codes 500, 501.

  • Name: FtpSyntaxError
  • Code: -605
  • Description: FTP_SYNTAX_ERROR
  • Type: ftp
const err = new chromiumNetErrors.FtpSyntaxError();
// or
const Err = chromiumNetErrors.getErrorByCode(-605);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FTP_SYNTAX_ERROR');
const err = new Err();

FtpCommandNotSupportedError

Server does not support the command we issued. FTP response codes 502, 504.

  • Name: FtpCommandNotSupportedError
  • Code: -606
  • Description: FTP_COMMAND_NOT_SUPPORTED
  • Type: ftp
const err = new chromiumNetErrors.FtpCommandNotSupportedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-606);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FTP_COMMAND_NOT_SUPPORTED');
const err = new Err();

FtpBadCommandSequenceError

Server rejected our command because we didn't issue the commands in right order. FTP response code 503.

  • Name: FtpBadCommandSequenceError
  • Code: -607
  • Description: FTP_BAD_COMMAND_SEQUENCE
  • Type: ftp
const err = new chromiumNetErrors.FtpBadCommandSequenceError();
// or
const Err = chromiumNetErrors.getErrorByCode(-607);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FTP_BAD_COMMAND_SEQUENCE');
const err = new Err();

Pkcs12ImportBadPasswordError

PKCS #12 import failed due to incorrect password.

  • Name: Pkcs12ImportBadPasswordError
  • Code: -701
  • Description: PKCS12_IMPORT_BAD_PASSWORD
  • Type: certificate-manager
const err = new chromiumNetErrors.Pkcs12ImportBadPasswordError();
// or
const Err = chromiumNetErrors.getErrorByCode(-701);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PKCS12_IMPORT_BAD_PASSWORD');
const err = new Err();

Pkcs12ImportFailedError

PKCS #12 import failed due to other error.

  • Name: Pkcs12ImportFailedError
  • Code: -702
  • Description: PKCS12_IMPORT_FAILED
  • Type: certificate-manager
const err = new chromiumNetErrors.Pkcs12ImportFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-702);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PKCS12_IMPORT_FAILED');
const err = new Err();

ImportCaCertNotCaError

CA import failed - not a CA cert.

  • Name: ImportCaCertNotCaError
  • Code: -703
  • Description: IMPORT_CA_CERT_NOT_CA
  • Type: certificate-manager
const err = new chromiumNetErrors.ImportCaCertNotCaError();
// or
const Err = chromiumNetErrors.getErrorByCode(-703);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('IMPORT_CA_CERT_NOT_CA');
const err = new Err();

ImportCertAlreadyExistsError

Import failed - certificate already exists in database. Note it's a little weird this is an error but reimporting a PKCS12 is ok (no-op). That's how Mozilla does it, though.

  • Name: ImportCertAlreadyExistsError
  • Code: -704
  • Description: IMPORT_CERT_ALREADY_EXISTS
  • Type: certificate-manager
const err = new chromiumNetErrors.ImportCertAlreadyExistsError();
// or
const Err = chromiumNetErrors.getErrorByCode(-704);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('IMPORT_CERT_ALREADY_EXISTS');
const err = new Err();

ImportCaCertFailedError

CA import failed due to some other error.

  • Name: ImportCaCertFailedError
  • Code: -705
  • Description: IMPORT_CA_CERT_FAILED
  • Type: certificate-manager
const err = new chromiumNetErrors.ImportCaCertFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-705);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('IMPORT_CA_CERT_FAILED');
const err = new Err();

ImportServerCertFailedError

Server certificate import failed due to some internal error.

  • Name: ImportServerCertFailedError
  • Code: -706
  • Description: IMPORT_SERVER_CERT_FAILED
  • Type: certificate-manager
const err = new chromiumNetErrors.ImportServerCertFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-706);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('IMPORT_SERVER_CERT_FAILED');
const err = new Err();

Pkcs12ImportInvalidMacError

PKCS #12 import failed due to invalid MAC.

  • Name: Pkcs12ImportInvalidMacError
  • Code: -707
  • Description: PKCS12_IMPORT_INVALID_MAC
  • Type: certificate-manager
const err = new chromiumNetErrors.Pkcs12ImportInvalidMacError();
// or
const Err = chromiumNetErrors.getErrorByCode(-707);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PKCS12_IMPORT_INVALID_MAC');
const err = new Err();

Pkcs12ImportInvalidFileError

PKCS #12 import failed due to invalid/corrupt file.

  • Name: Pkcs12ImportInvalidFileError
  • Code: -708
  • Description: PKCS12_IMPORT_INVALID_FILE
  • Type: certificate-manager
const err = new chromiumNetErrors.Pkcs12ImportInvalidFileError();
// or
const Err = chromiumNetErrors.getErrorByCode(-708);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PKCS12_IMPORT_INVALID_FILE');
const err = new Err();

Pkcs12ImportUnsupportedError

PKCS #12 import failed due to unsupported features.

  • Name: Pkcs12ImportUnsupportedError
  • Code: -709
  • Description: PKCS12_IMPORT_UNSUPPORTED
  • Type: certificate-manager
const err = new chromiumNetErrors.Pkcs12ImportUnsupportedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-709);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PKCS12_IMPORT_UNSUPPORTED');
const err = new Err();

KeyGenerationFailedError

Key generation failed.

  • Name: KeyGenerationFailedError
  • Code: -710
  • Description: KEY_GENERATION_FAILED
  • Type: certificate-manager
const err = new chromiumNetErrors.KeyGenerationFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-710);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('KEY_GENERATION_FAILED');
const err = new Err();

PrivateKeyExportFailedError

Failure to export private key.

  • Name: PrivateKeyExportFailedError
  • Code: -712
  • Description: PRIVATE_KEY_EXPORT_FAILED
  • Type: certificate-manager
const err = new chromiumNetErrors.PrivateKeyExportFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-712);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PRIVATE_KEY_EXPORT_FAILED');
const err = new Err();

SelfSignedCertGenerationFailedError

Self-signed certificate generation failed.

  • Name: SelfSignedCertGenerationFailedError
  • Code: -713
  • Description: SELF_SIGNED_CERT_GENERATION_FAILED
  • Type: certificate-manager
const err = new chromiumNetErrors.SelfSignedCertGenerationFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-713);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SELF_SIGNED_CERT_GENERATION_FAILED');
const err = new Err();

CertDatabaseChangedError

The certificate database changed in some way.

  • Name: CertDatabaseChangedError
  • Code: -714
  • Description: CERT_DATABASE_CHANGED
  • Type: certificate-manager
const err = new chromiumNetErrors.CertDatabaseChangedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-714);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_DATABASE_CHANGED');
const err = new Err();

DnsMalformedResponseError

DNS resolver received a malformed response.

  • Name: DnsMalformedResponseError
  • Code: -800
  • Description: DNS_MALFORMED_RESPONSE
  • Type: dns
const err = new chromiumNetErrors.DnsMalformedResponseError();
// or
const Err = chromiumNetErrors.getErrorByCode(-800);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DNS_MALFORMED_RESPONSE');
const err = new Err();

DnsServerRequiresTcpError

DNS server requires TCP

  • Name: DnsServerRequiresTcpError
  • Code: -801
  • Description: DNS_SERVER_REQUIRES_TCP
  • Type: dns
const err = new chromiumNetErrors.DnsServerRequiresTcpError();
// or
const Err = chromiumNetErrors.getErrorByCode(-801);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DNS_SERVER_REQUIRES_TCP');
const err = new Err();

DnsServerFailedError

DNS server failed. This error is returned for all of the following error conditions: 1 - Format error - The name server was unable to interpret the query. 2 - Server failure - The name server was unable to process this query due to a problem with the name server. 4 - Not Implemented - The name server does not support the requested kind of query. 5 - Refused - The name server refuses to perform the specified operation for policy reasons.

  • Name: DnsServerFailedError
  • Code: -802
  • Description: DNS_SERVER_FAILED
  • Type: dns
const err = new chromiumNetErrors.DnsServerFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-802);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DNS_SERVER_FAILED');
const err = new Err();

DnsTimedOutError

DNS transaction timed out.

  • Name: DnsTimedOutError
  • Code: -803
  • Description: DNS_TIMED_OUT
  • Type: dns
const err = new chromiumNetErrors.DnsTimedOutError();
// or
const Err = chromiumNetErrors.getErrorByCode(-803);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DNS_TIMED_OUT');
const err = new Err();

DnsCacheMissError

The entry was not found in cache or other local sources, for lookups where only local sources were queried. TODO(ericorth): Consider renaming to DNS_LOCAL_MISS or something like that as the cache is not necessarily queried either.

  • Name: DnsCacheMissError
  • Code: -804
  • Description: DNS_CACHE_MISS
  • Type: dns
const err = new chromiumNetErrors.DnsCacheMissError();
// or
const Err = chromiumNetErrors.getErrorByCode(-804);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DNS_CACHE_MISS');
const err = new Err();

DnsSearchEmptyError

Suffix search list rules prevent resolution of the given host name.

  • Name: DnsSearchEmptyError
  • Code: -805
  • Description: DNS_SEARCH_EMPTY
  • Type: dns
const err = new chromiumNetErrors.DnsSearchEmptyError();
// or
const Err = chromiumNetErrors.getErrorByCode(-805);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DNS_SEARCH_EMPTY');
const err = new Err();

DnsSortError

Failed to sort addresses according to RFC3484.

  • Name: DnsSortError
  • Code: -806
  • Description: DNS_SORT_ERROR
  • Type: dns
const err = new chromiumNetErrors.DnsSortError();
// or
const Err = chromiumNetErrors.getErrorByCode(-806);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DNS_SORT_ERROR');
const err = new Err();

DnsSecureResolverHostnameResolutionFailedError

Failed to resolve the hostname of a DNS-over-HTTPS server.

  • Name: DnsSecureResolverHostnameResolutionFailedError
  • Code: -808
  • Description: DNS_SECURE_RESOLVER_HOSTNAME_RESOLUTION_FAILED
  • Type: dns
const err = new chromiumNetErrors.DnsSecureResolverHostnameResolutionFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-808);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DNS_SECURE_RESOLVER_HOSTNAME_RESOLUTION_FAILED');
const err = new Err();

Author: Maxkueng
Source Code: https://github.com/maxkueng/chromium-net-errors 
License: MIT license

#electron #node #error