A compass consists of a freely-spinning magnetic pointer that aligns itself with the earth's magnetic field. By placing the pointer within a calibrated ring, your boat's heading can be determined to within a few degrees. While the earth's magnetic field is very strong, small magnetic fields that are close to the compass may cause it to point away from magnetic north. Swinging the compass is a process of adjusting small compensating magnets within the compass until the heading errors are minimized. On fiberglass or wooden boats without lots of steel, the deviation sources on board may be practically nil.
Electronic compasses are a modern variation on traditional compasses.
They measure the relative strength of magnetic fields passing through two coils of wire. Using sophisticated electronics, these sensors can deduce the direction of the earth's magnetic field. They are still affected by local magnetic fields like steel components and speaker magnets, but they can compensate electronically for those fields which do not change in strength or location. One advantage of electronic compasses is that their sensors may be mounted remotely in many cases. This allows you to place the sensor where it will be least affected by moving magnetic fields and the motion of the boat.