Neste tutorial, você aprenderá sobre o uso de caracteres e strings em Swift. Você também aprenderá diferentes operações que podem ser realizadas em strings e caracteres.
O que é um personagem?
Um caractere é um único símbolo (letra, número, etc.). Os caracteres em swift são do Character
tipo e são declarados como:
deixe algumCharacter: Character
Como declarar e atribuir um personagem em Swift?
Você pode atribuir um valor em tipo de caractere igual a String usando aspas duplas, " "
mas deve conter apenas um único caractere entre as aspas " "
.
Se você precisar incluir mais de um caractere, será necessário defini-lo em String
vez de Character
.
Exemplo 1: Declarando e atribuindo um personagem
let someCharacter:Character = “H” let specialCharacter:Character = “@” print(someCharacter) print(specialCharacter)
Quando você executa o programa, a saída será:
H @
Exemplo 2: Atribuição de mais de um caractere (não funciona)
Mas se você tentar atribuir dois símbolos dentro do personagem como
/* This will give an error Changing the type to String will fix it. */ let failableCharacter:Character = "H@" print(failableCharacter)
Ao tentar executar o código acima, você obterá um erro como:
Não é possível converter o valor do tipo String em Caractere.
Criação de personagem usando Unicode e sequência de escape
Você também pode criar tipos especiais de caracteres para emoji .eg usando Unicodes. Você pode criar um Unicode usando a sequência de escape u (n) (ponto de código Unicode, n está em hexadecimal).
Exemplo 3: Criação de um caractere Unicode
let heartShape:Character = "u(2665)" print(heartShape)
Quando você executa o programa, a saída será:
♥
No exemplo acima, um caractere em forma de coração foi criado a partir do código U+2665
. Embora u(2665)
esteja incluído entre aspas duplas, o compilador não o trata como um String
porque usamos uma sequência de escape u(n)
. Uma sequência de escape não representa a si mesma quando incluída em literal.
O que é uma corda?
Uma string é simplesmente uma coleção de caracteres. Strings em Swift são do String
tipo e declaradas como:
deixe someString: String
Como declarar e atribuir uma string em Swift?
Você pode atribuir valor no tipo String usando literais de string. Um literal de string é uma coleção de caracteres entre aspas duplas " "
.
Exemplo 4: Declarando e atribuindo uma string
let someString:String = "Hello, world!" let someMessage = "I love Swift." print(someString) print(someMessage)
Quando você executa o programa, a saída será:
Olá Mundo! Eu amo Swift.
Aqui, "Hello, world!"
e "I love Swift."
são literais de string usados para criar variáveis de string someString e someMessage, respectivamente.
Operações em uma corda
Existem algumas funções e propriedades integradas em String para lidar com as operações usadas com mais frequência. Por exemplo: para juntar strings, mude para maiúsculas ou maiúsculas. Vamos explorar algumas operações usadas com frequência abaixo:
Comparação de cordas
Você pode simplesmente verificar se duas strings são iguais ou não usando o operador de comparação (==)
. O operador retorna retorna true
se ambas as strings forem iguais, caso contrário, ele retorna false
.
Exemplo 5: comparação de strings em Swift
let someString = "Hello, world!" let someMessage = "I love Swift." let someAnotherMessage = "Hello, world!" print(someString == someMessage) print(someString == someAnotherMessage)
Quando você executa o programa, a saída será:
falso verdadeiro
Concatenação de string
Dois valores de strings diferentes podem ser adicionados junto com o operador de adição (+)
ou usando o operador de atribuição composto (+=)
. Você também pode anexar um caractere / string em uma string usando o append
método.
Exemplo 6: concatenação de string em Swift
let helloStr = "Hello, " let worldStr = "World" var result = helloStr + worldStr print(result) result.append("!") print(result)
Quando você executa o programa, a saída será:
Hello, World Hello, World!
No programa acima, criamos um resultado de string anexando helloStr e worldStr usando o operador +. Portanto, print(result)
exibe Hello, World na tela.
Você também pode anexar qualquer caractere ou string usando o append
método. result.append("!")
acrescenta um !
caractere no final da string. Portanto, as print(result)
saídas Hello, World! na tela.
Concatenação de strings usando operador de atribuição avançado
We can also use advanced assignment operator (+=) to append string.
Example 7: String concatenation using += operator
var helloStr = "Hello, " let worldStr = "World!" helloStr += worldStr print(helloStr)
When you run the program, the output will be:
Hello, World!
Notice the use of var instead of let in helloStr. If you have defined helloStr a constant using let, you cannot change it later using the +=
operator and eventually get an error. So, you have to define helloStr a variable.
String Interpolation
It is a simple process of evaluating a string literal that consists of variables, constants etc. Imagine you have player’s name and score stored in two constants as:
let playerName = "Jack" let playerScore = 99
Now you need to display a message to the player as "Congratulations Jack!. Your highest score is 99." Here, you need to a way to use the values of the constants in a single string.
This can be achieved using string concatenation as:
let congratsMessage = "Congratulations " + playerName + "!. Your highest score is " + playerScore + "." print(congratsMessage)
However, you can see this can get messy pretty soon. You have to take care of the spaces after the word Congratulations
, is
. Also, if you have to use more than two constants/variables, it will get unreadable.
There’s an easier way to display the message using string interpolation. Interpolation is the process to include value of a variable or constant inside string literal.
The variable or constant that should insert into the string literal is wrapped in a pair of parentheses ( )
, prefixed by a backslash ()
.
Example 8: String interpolation in Swift
let playerName = "Jack" let playerScore = 99 let congratsMessage = "Congratulations (playerName)!. Your highest score is (playerScore)." print(congratsMessage)
When you run the program, the output will be:
Congratulations Jack!. Your highest score is 99.
Some helpful built-in String functions & variables:
1. isEmpty
This function determines if a string is empty or not. It returns true
if the string is empty otherwise, it returns false
.
Example 9: isEmpty
var emptyString = "" print(emptyString.isEmpty)
When you run the program, the output will be:
true
2. capitalized
This property is used to capitalize every word in a string.
Example 10: capitalized
let someString = "hello, world!" print(someString.capitalized)
When you run the program, the output will be:
Hello, World!
3. uppercased and lowercased
The uppercased function converts string to uppercase letter and the lowercased function converts string to lowercase letter.
Example 11: uppercased() and lowercased()
let someString = "Hello, World!" print(someString.uppercased()) print(someString.lowercased())
When you run the program, the output will be:
HELLO, WORLD! hello, world!
4. Length/count
This property is used to count the total number of characters in a string.
Example 12: count
let someString = "Hello, World!" print(someString.count)
When you run the program, the output will be:
13
5. hasPrefix
Esta função determina se uma string começa com certos caracteres ou não e retorna um valor booleano. Ele retorna true
se o prefixo da string corresponder ao valor fornecido, caso contrário, retorna false
.
Exemplo 13: hasPrefix ()
let someString = "Hello, World!" print(someString.hasPrefix("Hell")) print(someString.hasPrefix("hell"))
Quando você executa o programa, a saída será:
verdadeiro falso
6. hasSuffix
Esta função determina se uma string termina com certos caracteres ou não e retorna um valor booleano. Ele retorna true
se o sufixo da string corresponde ao valor fornecido, caso contrário, retorna false
.
Exemplo 14: hasSuffix ()
print(someString.hasSuffix("rld!")) print(someString.hasSuffix("Rld!"))
Quando você executa o programa, a saída será:
verdadeiro falso