When can I swap around the order of operators? I was doing this question:

Using $\left< x \middle| p\right> = \frac{1}{\sqrt{2 \pi \hbar}}e^{ipx/\hbar}$ show that:
$$ \left<x \middle| \hat{p} \middle| \psi \right> = -i\hbar \frac{d}{dx} \left< x \middle| \psi\right> $$
  for a general $\psi$.


Method 1 (how my lecturer did it)
\begin{align*}
\left<x \middle| \hat{p} \middle| \psi \right> &= \int dp \, \left<x \middle| p\right> \left<p \middle| \hat{p} \middle| \psi \right> \\
&= \int dp \, p \frac{1}{\sqrt{2 \pi \hbar}}e^{ipx/\hbar} \left<p \middle|\psi\right> \\
&= \int dp \, (-i\hbar) \frac{d}{dx}\left<x \middle| p\right>\left<p\middle|\psi\right> \\
&= -i\hbar \frac{d}{dx}\left<x \middle|\psi\right>
\end{align*}
Here I want to ask:


*

*Why do put it in integral form? (See below why I think it's unnessessary)

*Why are we allowed to swap the operator order like we did in line 3?

Method 2 (how I did it seeing that we can just swap the order)
\begin{align*}
\left<x \middle| \hat{p} \middle| \psi \right> &= \left<x \middle| p\right> \left<p \middle| \hat{p} \middle| \psi \right> \\
&= \hat{p} \left<x \middle|p\right>\left<p\middle|\psi\right> \\
&= \hat{p} \left<x \middle| \psi\right> \\
&= - i \hbar \frac{d}{dx} \left< x\middle| \psi\right>
\end{align*}
I don't understand why putting it in integral form is even correct? 
 A: Your lecturer got the eigenvalue using the fact that the operator $\hat{p}$ is Hermitian so you can do this:
\begin{align}
    \langle p| \hat{p} &= \left( \hat{p}^\dagger |p\rangle\right)^\dagger\\
     &= \left( \hat{p} |p\rangle\right)^\dagger\\
     &= \left( p |p\rangle\right)^\dagger\\
     &= \langle p| p
\end{align}
I think it becomes a bit neater if you put the projector $|p\rangle\langle p|$ after the operator $\hat{p}$ because then you don't have to do the gymnastics with the Hermitian conjugate. This would be my attempt (being as explicit as possible at each step):
\begin{align}
\langle x|\hat{p} |\psi\rangle &= \int dp \langle x|\hat{p} |p\rangle\langle p|\psi\rangle\\
&= \int dp p \langle x |p\rangle\langle p|\psi\rangle\\
&= \int dp p e^{\frac{i}{\hbar}xp}\langle p|\psi\rangle\\
&= \int dp \left(-i\hbar \frac{d}{dx}\right) e^{\frac{i}{\hbar}xp}\langle p|\psi\rangle\\
&= \left(-i\hbar \frac{d}{dx}\right)\int dp  e^{\frac{i}{\hbar}xp}\langle p|\psi\rangle\\
&= \left(-i\hbar \frac{d}{dx}\right)\int dp  \langle x|p\rangle\langle p|\psi\rangle\\
&= \left(-i\hbar \frac{d}{dx}\right)\langle x|\psi\rangle\\
\end{align}
Note that it is the number $p$ that is brought to the front in line two not the operator $\hat{p}$. We choose the states $|p\rangle$ so that we have the following equality: $\hat{p}|p\rangle = p|p\rangle$.
