Unable to format internal drive as APFS on 2018 MacBook Pro

Below are three examples of how to erase the drive and create a APFS volume named MyVolume. You only need to follow one of the examples.

  • The commands given below create a Mac OS Extended (Journaled) partition, then reformat to APFS.

    diskutil eraseDisk JHFS+ dummy GPT disk0
    diskutil apfs create disk0s2 MyVolume
    
  • The commands given below create a Mac OS Extended (Journaled) partition, then convert to APFS.

    diskutil eraseDisk JHFS+ myVolume GPT disk0
    diskutil apfs convert disk0s2
    
  • The commands given below create a Mac OS Extended (Journaled) partition, then convert to an empty APFS container. Finally an APFS volume is added to the container..

    diskutil eraseDisk JHFS+ dummy GPT disk0
    diskutil apfs createContainer disk0s2
    Container=$(diskutil info disk0s2 | grep Container)
    diskutil apfs addVolume "${Container##* }" APFS myVolume