Dictionary now gives error 'not convertible to

2020-07-18 08:35发布

问题:

I'm was just getting my head around Swift - then came Swift 1.2 (breaking my working code)!

I have a function based on the code sample from NSHipster - CGImageSourceCreateThumbnailAtIndex.

My previously working code is:

import ImageIO

func processImage(jpgImagePath: String, thumbSize: CGSize) {

    if let path = NSBundle.mainBundle().pathForResource(jpgImagePath, ofType: "") {
        if let imageURL = NSURL(fileURLWithPath: path) {
            if let imageSource = CGImageSourceCreateWithURL(imageURL, nil) {

                let maxSize = max(thumbSize.width, thumbSize.height) / 2.0

                let options = [
                    kCGImageSourceThumbnailMaxPixelSize: maxSize,
                    kCGImageSourceCreateThumbnailFromImageIfAbsent: true
                ]

                let scaledImage = UIImage(CGImage: CGImageSourceCreateThumbnailAtIndex(imageSource, 0, options))

                // do other stuff
            }
        }
    }
}

Since Swift 1.2, the compiler provides two errors relating to the options dictionary:

  1. Type of expression is ambiguous without more context
  2. '_' is not convertible to 'BooleanLiteralConvertible' (in ref to 'true' value)

I have tried a variety ways to specifically declare the types in the options dictionary (eg. [String : Any], [CFString : Any], [Any : Any] ). While this may solve one error, they introduce other errors.

Can anyone please illuminate me?? More importantly, can anyone please explain what changed with Swift 1.2 and dictionaries that stopped this from working.

回答1:

From the Xcode 6.3 release notes:

The implicit conversions from bridged Objective-C classes (NSString/NSArray/NSDictionary) to their corresponding Swift value types (String/Array/Dictionary) have been removed, making the Swift type system simpler and more predictable.

The problem in your case are the CFStrings like kCGImageSourceThumbnailMaxPixelSize. These are not automatically converted to String anymore. Two possible solutions:

let options = [
    kCGImageSourceThumbnailMaxPixelSize as String : maxSize,
    kCGImageSourceCreateThumbnailFromImageIfAbsent as String : true
]

or

let options : [NSString : AnyObject ] = [
    kCGImageSourceThumbnailMaxPixelSize:  maxSize,
    kCGImageSourceCreateThumbnailFromImageIfAbsent: true
]