">
 

Swift Arrays

Iniciado por joomlamz, 01 de Junho de 2026, 11:00

Respostas: 1   |   Visualizações: 20

Tópico anterior - Tópico seguinte

0 Membros e 1 Visitante estão a ver este tópico.

Olá a todos os membros do fórum webmastersmz.com! Hoje, vamos discutir um tópico muito importante relacionado à segurança de websites que utilizam a plataforma WordPress. O artigo "Critical WP Maps Pro Flaw Actively Exploited to Create Admin Accounts" destaca uma vulnerabilidade crítica no plugin WP Maps Pro que está sendo ativamente explorada por atacantes para criar contas de administrador em websites vulneráveis.

Os pontos principais desta vulnerabilidade incluem:

* A existência de uma falha no código do plugin WP Maps Pro que permite a criação de contas de administrador sem a necessidade de autenticação;
* A capacidade dos atacantes de explorar esta vulnerabilidade para obter acesso não autorizado a websites que utilizam o plugin;
* A possibilidade de os atacantes realizarem ações maliciosas, como roubo de dados, modificação de conteúdo e instalação de malware.

É fundamental que os webmasters e administradores de websites que utilizam o plugin WP Maps Pro tomem medidas imediatas para proteger seus websites. Isso inclui atualizar o plugin para a versão mais recente, monitorar os logs de acesso e atividade do website, e implementar medidas de segurança adicionais, como autenticação de dois fatores e firewalls de aplicativos web.

Além disso, é importante lembrar que a segurança de um website é um processo contínuo e que os webmasters devem estar sempre atentos às últimas ameaças e vulnerabilidades. O fórum webmastersmz.com é um ótimo lugar para discutir e compartilhar conhecimentos sobre segurança de websites e outras questões relacionadas à tecnologia.

Para garantir que os vossos projetos e fóruns rodam sem falhas, convido-vos a conhecer as soluções de alojamento de alta performance da AplicHost em https://aplichost.com. A AplicHost oferece soluções de alojamento personalizadas e seguras, com suporte técnico especializado e recursos de alta performance para garantir que os vossos websites e aplicativos funcionem sem interrupções. Além disso, a AplicHost também oferece soluções de segurança avançadas, como firewalls de aplicativos web e sistemas de detecção de intrusos, para proteger os vossos websites contra ameaças e vulnerabilidades. Vamos conversar mais sobre isso no fórum!

Swift Arrays



Tópico: Swift Arrays
Categoria: Tutoriais | Programação & Tecnologia
Idioma Principal: Português (Conteúdo de Tecnologia)

Descrição do Conteúdo / Informações:
-------------------------------------------------------------------------
So far in our Swift journey, we've worked with single values — a name here, a number there. But what happens when you need to store a whole squad of values? 🤔

That's where arrays come in.



🧠 Why Do Arrays Exist?


Imagine you're building an app that tracks all the characters from Attack on Titan. You could do this:

let character1 = "Eren"
let character2 = "Mikasa"
let character3 = "Armin"
let character4 = "Levi"

Sure, that works for four characters. But what about all 100+ members of the Survey Corps? 😅 That approach falls apart fast.

This is exactly why Swift gives us arrays — a single place to store as many values as you need, always in the order you added them.



📦 Creating Your First Array


Arrays use square brackets [], with commas between each item:

var surveyCorps = ["Eren", "Mikasa", "Armin", "Levi"]
let episodeCounts = [13, 12, 22, 16, 28]
var ratings = [9.8, 8.7, 9.5, 7.6]

Three things to notice here:


Strings → wrapped in quotes ""


Integers → plain numbers


Doubles → numbers with a decimal point

Swift is smart enough to figure out the type of each array just by looking at what's inside. 🧐



🔢 Reading Values — Zero Indexing


Here's the part that trips up almost every beginner (don't worry, it gets natural fast):

Arrays in Swift start counting from 0, not 1.

This is called zero-based indexing. So:

Position
Index
Value

1st
"Eren"

2nd
[1]
"Mikasa"

3rd
[2]
"Armin"

4th
[3]
"Levi"

print(surveyCorps[0]) // Eren
print(surveyCorps[1]) // Mikasa
print(surveyCorps[3]) // Levi

⚠️ Watch out! If you try to access an index that doesn't exist, Swift will crash your app on purpose. For example:

print(surveyCorps[99]) // 💥 CRASH

That might sound scary, but it's actually Swift protecting you. If it didn't crash, you'd silently get back garbage data — which is way worse than a crash you can see and fix. Think of it as Swift saying "Hey! That character doesn't exist in this arc!" 😤



➕ Adding Items to an Array


If your array is a var (variable), you can keep adding to it using .append():

var surveyCorps = ["Eren", "Mikasa", "Armin"]

surveyCorps.append("Levi")
surveyCorps.append("Hange")
surveyCorps.append("Connie")

print(surveyCorps)
// ["Eren", "Mikasa", "Armin", "Levi", "Hange", "Connie"]

You can even append the same value more than once — Swift won't stop you:

surveyCorps.append("Eren") // Eren again? Okay then 😅



🚫 Type Safety — One Type Per Array


Swift is very strict about this: an array can only hold one type of data.

var ratings = [9.8, 8.7, 9.5]
ratings.append("Mikasa") // ❌ ERROR — can't add a String to a Double array

This is type safety in action. Once Swift knows your array holds Double values, it won't let anything else sneak in. This keeps your data clean and your app stable. 🔒



🏗️ Creating Empty Arrays


Sometimes you don't have data yet — you want to start empty and fill it in as you go. Here are two ways to do that:

Explicit syntax:

var titanShifters = Array<String>()
titanShifters.append("Attack Titan")
titanShifters.append("Armored Titan")
titanShifters.append("Colossal Titan")

Shorthand syntax (more common):

var titanShifters = [String]()
titanShifters.append("Attack Titan")
titanShifters.append("Armored Titan")
titanShifters.append("Colossal Titan")

Both do exactly the same thing. The second one is what you'll see most in the wild. 🌿



🛠️ Useful Array Operations




📏 Count — How many items?


var surveyCorps = ["Eren", "Mikasa", "Armin", "Levi"]
print(surveyCorps.count) // 4



🗑️ Remove Items


var titans = ["Attack", "Armored", "Colossal", "Beast", "War Hammer"]

titans.remove(at: 2)   // Removes "Colossal"
print(titans.count)    // 4

titans.removeAll()     // Wipes everything
print(titans.count)    // 0



🔍 Check if Something Exists — contains()


let seasons = ["Season 1", "Season 2", "Season 3", "The Final Season"]
print(seasons.contains("Season 4"))          // false
print(seasons.contains("The Final Season"))  // true



🔤 Sort Your Array — sorted()


let characters = ["Reiner", "Annie", "Bertholdt", "Zeke"]
print(characters.sorted())
// ["Annie", "Bertholdt", "Reiner", "Zeke"]

sorted() returns a new sorted array — the original stays unchanged. Neat! ✨

For numbers, it sorts smallest → largest:

let episodes = [7, 1, 22, 13, 4]
print(episodes.sorted()) // [1, 4, 7, 13, 22]



🔄 Reverse an Array — reversed()


let arcs = ["Trost", "Female Titan", "Clash of Titans", "Return to Shiganshina"]
let reversed = Array(arcs.reversed())
print(reversed)
// ["Return to Shiganshina", "Clash of Titans", "Female Titan", "Trost"]

💡 Pro tip: Swift doesn't actually rearrange the items when you call reversed(). It just remembers you want them reversed — lazy in the best possible way. Wrapping it in Array() gives you a plain array back.



🧩 Putting It All Together


Here's a mini program using everything we covered:

// Starting lineup
var squadMembers = ["Eren", "Mikasa", "Armin"]

// Add more members
squadMembers.append("Levi")
squadMembers.append("Hange")

// Check the roster
print("Squad size: \(squadMembers.count)") // 5

// Is Zeke in the squad?
print(squadMembers.contains("Zeke")) // false

// Sort alphabetically
print(squadMembers.sorted())
// ["Armin", "Eren", "Hange", "Levi", "Mikasa"]

// Remove Eren (he went rogue 😬)
squadMembers.remove(at: 0)
print(squadMembers.count) // 4



🧵 Quick Recap


Feature
What it does
Example

[]
Create an array
var names = ["A", "B"]

Access by index
names[0]

.append()
Add an item
names.append("C")

.count
Total items
names.count

.contains()
Check existence
names.contains("A")

.sorted()
Sort (new array)
names.sorted()

.reversed()
Reverse (new array)
names.reversed()

.remove(at:)
Remove by index
names.remove(at: 0)

.removeAll()
Wipe the array
names.removeAll()



🎯 Why This Matters


Arrays are everywhere in real apps. Every list you see on screen — messages, contacts, search results, leaderboards — is backed by an array under the hood. Getting comfortable with them early is one of the best investments you can make as a Swift developer. 💪

Next up, we'll look at dictionaries — another way to store data, but with labels instead of positions. See you there! 👋


Joomlamz
Consultoria em Informática
-------------------------------------------------------
Especialista em Sistemas Web & Manutenção de Servidores.
A desenvolver o novo AplPortal com suporte a PHP 8.
Precisa de ajuda profissional? Contacte-me.

Tags: