How to use sizeof() method in Swift 4

6.2k Views Asked by At

I am trying to implement this code which I got from an apple WWDC video. However the video is from 2016 and I think the syntax has changed. How do I call sizeof(Float)? This produces an error.

func render(buffer:AudioBuffer){
    let nFrames = Int(buffer.mDataByteSize) / sizeof(Float)
    var ptr = UnsafeMutableRawPointer(buffer.mData)
    var j = self.counter
    let cycleLength = self.sampleRate / self.frequency
    let halfCycleLength = cycleLength / 2
    let amp = self.amplitude, minusAmp = -amp
    for _ in 0..<nFrames{
        if j < halfCycleLength{
            ptr.pointee = amp
        } else {
            ptr.pointee = minusAmp
        }
        ptr = ptr.successor()
        j += 1.0
        if j > cycleLength {

        }
    }
    self.counter = j
}
1

There are 1 best solutions below

0
On

The sizeof() function is no longer supported in Swift.

As Leo Dabus said in his comment, you want MemoryLayout<Type>.size, or in your case, MemoryLayout<Float>.size.

Note that tells you the abstract size of an item of that type. However, due to alignment, you should not assume that structs containing different types of items will be the sums of the sizes of the other elements. Also, you need to consider the device it's running on. On a 64 bit device, Int is 8 bytes. On a 32 bit device, it's 4 bytes.

See the article on MemoryLayout at SwiftDoc.org for more information.