Let $X_i$ be the random variable which is 1 when person $i$ leaves with their own hat and 0 otherwise. Then $$E[X_i]= 1\cdot P(X_i=1)=\dfrac{1}{n}$$ and $$\mathrm{Var}[X_i]= 1^2\cdot P(X_i=1)-E[X_i]^2=\dfrac{1}{n}-\dfrac{1}{n^2}=\dfrac{n-1}{n^2},$$ while $X=\sum_{i=1}^nX_i$ is the random variable which counts the number of people who leave with their own hats.
Now the $X_i$ are not independent, but still $E[X]=\sum_{i=1}^n E[X_i] = 1$.
However, for $\mathrm{Var}[X]$ you need the result $$\mathrm{Var}[X]=\sum_{i=1}^n \mathrm{Var}[X_i]+ 2\sum_{i=1}^{n-1} \sum_{j=i+1}^n \mathrm{Cov}[X_i,X_j]= n\mathrm{Var}[X_1]+ n(n-1) \mathrm{Cov}[X_1,X_2].$$
and calculate
$$\mathrm{Cov}[X_1,X_2]= 1^2\cdot P(X_1=1 \;\mathrm{\&}\; X_2=1)-E[X_1] E[X_2]=\dfrac{1}{n(n-1)}-\dfrac{1}{n^2}=\dfrac{1}{n^2(n-1)},$$ so finally $\mathrm{Var}[X]= \dfrac{n-1}{n}+ \dfrac{1}{n} =1$.