Created
July 8, 2022 20:12
-
-
Save mateuspestana/062bf80db097692c510c6c067800aab1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// CONDITIONS | |
let score = 85 | |
if score > 80 { | |
print("Boa!") | |
} | |
// Aqui temos uma condição IF, seguida da condição em si (score maior que 80). Se a resposta disso for true, ele executa o comando entre {}. | |
let speed = 88 | |
let percentage = 85 | |
let age = 18 | |
if speed >= 88 { | |
print("Para onde vamos não precisamos de estradas.") | |
} | |
if percentage < 85 { | |
print("CAVALO") | |
} | |
if age >= 18 { | |
print("Digita 13 na urna e confirma") | |
} | |
// Aqui temos vários IFs juntos. | |
let ourName = "Dave Lister" | |
let friendName = "Arnold Rimmer" | |
if ourName < friendName { | |
print("It's \(ourName) vs \(friendName)") | |
} | |
if ourName > friendName { | |
print("It's \(friendName) vs \(ourName)") | |
} | |
// O parâmetro de comparação > também serve para ordem alfabética. | |
var username = "taylorswift13" | |
if username == "" { | |
username = "Anonymous" | |
} | |
print("Welcome, \(username)!") | |
// Se o usuário estiver em branco (ou seja, ""), trocar por Anonymous. Mas há outra forma de fazer isso: | |
var username2 = "" | |
if username2.count == 0 { | |
username2 = "Anonymous" | |
} | |
print("Welcome, \(username2)!") | |
// Mas isso não é muito rápido. Então podemos fazer: | |
var username3 = "" | |
if username3.isEmpty { | |
username3 = "Anônimo! Buh" | |
} | |
print("Welcome, \(username3)!") | |
// Poderíamos também fazer username3.isEmpty == true, mas é redundante, pois já se exige uma resposta verdadeira. | |
/// Múltiplas condições | |
let idade = 15 | |
if idade >= 18 { | |
print("You can vote in the next election.") | |
} else { | |
print("Sorry, you're too young to vote.") | |
} | |
// Usamos else ou else if para adicionar uma nova possibilidade à condição. Podemos usar também else if para uma nova checagem, mas somente podemos usar UM else, pois se TUDO ANTES DEU ERRADO, o ELSE resolverá. | |
var temp = 25 | |
if temp > 20 && temp < 30 { | |
print("It's a nice day.") | |
} | |
// Podemos ter múltiplas condições usando o && e as duas precisam ser verdadeiras. Se fosse apenas uma delas verdadeira, aí usaríamos ||, que é o OR. | |
let userAge = 14 | |
let hasParentalConsent = true | |
if userAge >= 18 || hasParentalConsent { | |
print("Você pode comprar essa revista!") | |
} | |
// Exercício: criar um ENUM chamado TransportOption que contém os casos: avião, helicóptero, bicicleta, carro e scooter. Atribuimos uma constante e rodamos algumas checagens: | |
enum TransportOption { | |
case avião, helicóptero, bicicleta, carro, scooter | |
} | |
let transport = TransportOption.avião | |
if transport == .avião || transport == .helicóptero { | |
print("Vamos voar!") | |
}else if transport == .bicicleta { | |
print("Vamos pela ciclovia!") | |
}else if transport == .carro { | |
print("Hora de ficar preso no engarrafamento... 😢") | |
}else { | |
print("Vou de scooter!") | |
} | |
// Repare, Matheus do futuro/querido leitor: o Swift entende que eu estou falando de transport.avião, então não preciso botar transport antes, só o .avião já satisfaz, pois dentro de transport já consta .avião. | |
/// SWITCH STATEMENTS | |
// Quando temos muitos casos, o ideal é usar um SWITCH, e não um IF. | |
enum Weather { | |
case sun, rain, wind, snow, unknown | |
} | |
let forecast = Weather.sun | |
switch forecast { | |
case .sun: | |
print("Dia lindo!") | |
case .rain: | |
print("Pega o guarda-chuva") | |
case .wind: | |
print("Que ventania!") | |
case .snow: | |
print("Leva o cachecol!") | |
case .unknown: | |
print("A previsão do tempo está indisponível.") | |
} | |
// O Switch PRECISA ser EXAUSTIVO. Sempre. Todos os casos precisam ser contemplados. E caso um caso não possa ser previsto (por não existir num ENUM, ou sei lá), ele pod eentrar no argumento default: | |
let place = "Metropolis" | |
switch place { | |
case "Gotham": | |
print("You're Batman!") | |
case "Mega-City One": | |
print("You're Judge Dredd!") | |
case "Wakanda": | |
print("You're Black Panther!") | |
default: | |
print("Who are you?") | |
} | |
// O switch vai parar no caso em que for dado como verdadeiro, não avançando para o próximo, o que otimiza o código. Se quiser passar e testar o próximo, usamos o fallthrough: | |
let day = 5 | |
print("Meu amor me deu...") | |
switch day { | |
case 5: | |
print("5 anéis de ouro") | |
fallthrough | |
case 4: | |
print("4 passarinhos") | |
fallthrough | |
case 3: | |
print("3 flores") | |
fallthrough | |
case 2: | |
print("2 empadinhas") | |
fallthrough | |
default: | |
print("O seu coraçao") | |
} | |
// Isso aqui ficou um pouco obscuro pra mim, no sentido de "quando vou utilizar?" mas é isso. Veremos mais pra frente. | |
// Putz, anotei isso e o último parágrafo da explicação vinha: PS: I’ve covered the fallthrough keyword because it’s important to folks coming from other programming languages, but it’s fairly rare to see it used in Swift – don’t worry if you’re struggling to think up scenarios when it might be useful, because honestly most of the time it isn’t! | |
/// OPERADOR TERNÁRIO | |
// O operador ternário lida com 3 informações: ele testa um valor em relação a outros dois. É como se fosse um ifelse do R: se uma condição bate, um valor, se não, outro. | |
let idadeVoto = 16 | |
let podeVotar = idadeVoto >= 16 ? "Sim" : "Não" | |
print(podeVotar) | |
// Lembrar de W?T:F what, true, false. Assim: | |
// What: idade >= 16. | |
// TRUE: "Sim" | |
// : | |
// FALSE: "Não" | |
let hour = 23 | |
print(hour < 12 ? "Bom dia" : "Boa tarde") | |
let names = ["Eric", "Weslley", "Gabriela"] | |
let contaAmigos = names.isEmpty ? "Ninguém" : "\(names.count) amigos" | |
print(contaAmigos) | |
enum Theme { | |
case light, dark | |
} | |
let theme = Theme.dark | |
let background = theme == .dark ? "black" : "white" | |
print(background) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment