Ordenar una array en Swift

Swift admite diferentes tipos de colecciones y la array es una de ellas. Una array es una colección ordenada del mismo tipo de valores como int, string, float, etc., no puede almacenar el valor de otro tipo en una array (por ejemplo, un tipo int solo puede almacenar valores enteros, no valor de string). Es una colección genérica y puede almacenar valores duplicados del mismo tipo. Si se asigna una array a una variable, entonces esa array es mutable, lo que significa que puede cambiar el contenido y el tamaño de la array. Si se asigna una array a una constante, esa array es inmutable, lo que significa que no puede cambiar el contenido ni el tamaño de la array. En Swift, también podemos ordenar arreglos en orden ascendente y descendente. Para ordenar la array usamos la función sort(). Esta función se utiliza para clasificar los elementos de la array en un orden específico, ya sea en orden ascendente o descendente. Utiliza el operador «>» para ordenar la array en orden descendente y el operador «<» para ordenar la array en orden ascendente. De forma predeterminada, este método ordena la array en orden ascendente. 

Sintaxis:

arrayName.ordenar (por: operador)

Aquí, 

arrayName es el nombre del objeto de array

Parámetro: este método solo toma un parámetro que es opcional. Si pasamos menos que el operador (<) en este método, ordenará la array en orden ascendente. Mientras que si pasamos el operador mayor que (>) en este método, ordenará la array en orden descendente.

Valor devuelto: este método no devuelve ningún valor, en lugar de un valor, cambiará el orden de la array. 

Ejemplo:

Swift

// Swift program to sort the array
import Swift
  
// Creating an array of Authors Name
// Here the array is of string type
var AuthorName = ["Rohit", "Poonam", "Anu", "Susmita", "Buvan", "Mohit"]
  
print("Author's name before sorting:", AuthorName)
  
// Sorting the AuthorName array
// Using sort() function
AuthorName.sort()
  
// Displaying the final result
print("Author's name after sorting:", AuthorName)
  
// Creating an array of article numbers
// Here the array is of int type
var ArticleNumber = [23, 1, 90, 3, 56, 23, 0, 6, 12]
print("----------------------")
  
print("Article numbers before sorting:", ArticleNumber)
  
// Sorting the ArticleNumber array
// Using sort() function
ArticleNumber.sort()
  
// Displaying the final result
print("Article numbers after sorting:", ArticleNumber)

Producción:

Author's name before sorting: ["Rohit", "Poonam", "Anu", "Susmita", "Buvan", "Mohit"]
Author's name after sorting: ["Anu", "Buvan", "Mohit", "Poonam", "Rohit", "Susmita"]
----------------------
Article numbers before sorting: [23, 1, 90, 3, 56, 23, 0, 6, 12]
Article numbers after sorting: [0, 1, 3, 6, 12, 23, 23, 56, 90]

Clasificación de array en orden ascendente

Podemos ordenar la array en orden ascendente pasando menos que el operador (<) en la función sort(). 

Sintaxis:

arrayName.ordenar (por: <)

Aquí, 

arrayName es el nombre del objeto de array

Ejemplo:

Swift

// Swift program to sort the array in ascending Order
import Swift
  
// Creating an array of Authors Name
// Here the array is of string type
var AuthorName = ["Sumit", "Neha", "Anu", "Susmita", "Buvan", "Govind"]
  
print("Author's name before sorting:", AuthorName)
  
// Sorting the AuthorName array in ascending Order
// By passing less than operator(<) in sort() function
AuthorName.sort(by:<)
  
// Displaying the final result
print("Author's name after sorting:", AuthorName)
  
// Creating an array of article numbers
// Here the array is of int type
var ArticleNumber = [3, 20, 10, 3, 86, 23, 0, 699, 12]
print("----------------------")
  
print("Article numbers before sorting:", ArticleNumber)
  
// Sorting the ArticleNumber array in ascending Order
// By passing less than operator(<) in sort() function
ArticleNumber.sort(by:<)
  
// Displaying the final result
print("Article numbers after sorting:", ArticleNumber)

Producción:

Author's name before sorting: ["Sumit", "Neha", "Anu", "Susmita", "Buvan", "Govind"]
Author's name after sorting: ["Anu", "Buvan", "Govind", "Neha", "Sumit", "Susmita"]
----------------------
Article numbers before sorting: [3, 20, 10, 3, 86, 23, 0, 699, 12]
Article numbers after sorting: [0, 3, 3, 10, 12, 20, 23, 86, 699]

Clasificación de array en orden descendente

Podemos ordenar la array en orden descendente pasando el operador mayor que (>) en la función sort(). 

Sintaxis:

arrayName.ordenar (por: >)

Aquí, 

arrayName es el nombre del objeto de array

Ejemplo:

Swift

// Swift program to sort the array in descending Order
import Swift
  
// Creating an array of Authors Name
// Here the array is of string type
var AuthorName = ["Punit", "Neha", "Amu", "Susmita", "Fiza", "Govind"]
  
print("Author's name before sorting:", AuthorName)
  
// Sorting the AuthorName array in descending Order
// By passing greater than operator(>) in sort() function
AuthorName.sort(by:>)
  
// Displaying the final result
print("Author's name after sorting:", AuthorName)
  
// Creating an array of article numbers
// Here the array is of int type
var ArticleNumber = [3, 20, 10, 3, 86, 23, 0, 699, 12]
print("----------------------")
  
print("Article numbers before sorting:", ArticleNumber)
  
// Sorting the ArticleNumber array in descending Order
// By passing greater than operator(>) in sort() function
ArticleNumber.sort(by:>)
  
// Displaying the final result
print("Article numbers after sorting:", ArticleNumber)

Producción:

Author's name before sorting: ["Punit", "Neha", "Amu", "Susmita", "Fiza", "Govind"]
Author's name after sorting: ["Susmita", "Punit", "Neha", "Govind", "Fiza", "Amu"]
----------------------
Article numbers before sorting: [3, 20, 10, 3, 86, 23, 0, 699, 12]
Article numbers after sorting: [699, 86, 23, 20, 12, 10, 3, 3, 0]

Publicación traducida automáticamente

Artículo escrito por ankita_saini y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *