Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use sizeof() method in Swift 4

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
}
like image 960
dmann200 Avatar asked Oct 15 '25 20:10

dmann200


1 Answers

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.

like image 95
Duncan C Avatar answered Oct 17 '25 13:10

Duncan C



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!