0

I have written an extension to resize a given image:

extension NSImage {
    func resizeImage(width: CGFloat, _ height: CGFloat) -> NSImage {
        let img = NSImage(size: CGSize(width:width, height:height))

        img.lockFocus()
        let ctx = NSGraphicsContext.current()
        ctx?.imageInterpolation = .high
        self.draw(in: NSMakeRect(0, 0, width, height), from: NSMakeRect(0, 0, size.width, size.height), operation: .copy, fraction: 1)
        img.unlockFocus()

        return img
    }
}

But I don't know how to use it within a for loop:

for image in images
{
   image.resizeImage(width: CGFloat(rwidth),CGFloat(rheight))
   // I intent to resize the image and save it to a file
   // resize -> save to local file
}

This does not work... nor I can assign the resized image to the old one. Should I create a temporary variable, assign the resized image to it and save it? This would be waste of memory I guess.

How can I solve this problem?

techno
  • 6,100
  • 16
  • 86
  • 192

1 Answers1

1

You can't mutate a variable in an extension in Swift. You have to initialize a second array.

Use map for a one-liner:

let resizedImages = images.map { $0.resizeImages(width: CGFloat(rwidth), CGFloat(rheight)) }
Tamás Sengel
  • 55,884
  • 29
  • 169
  • 223
  • Thanks ...but I don't intent to store the images in the array .. what I do in the loop is save the image to a file.Before saving I need to resize the image.What would be a cleaner approach to do this. – techno Oct 05 '17 at 09:37