Ambiguous use of init(contentsOfURL:)

Hello I Use XCode 9.3 and Swift 4.1

Below my code:


import SolarMaxIosFramework

var upsList = [Any]()

class initUps {

// print("InitUps Initialization")

func loadUpsValues () {

print("loadUpsValues")

let upsFileAsURL = URL(string: "Upslist.txt")

// Original ObjectiveC: NSMutableArray *ListUpsArray = [NSMutableArray arrayWithContentsOfURL:upsFile];

let upsList = NSArray(contentsOfURL:upsFileAsURL! ) // Error

}

}


I Get an error : Ambiguous use of init(contentsOfURL:)

It seems this error indicates that two frameworks gives a definition of NSArray

1. Found this candidate (Foundation.NSArray)

2. Found this candidate (Foundation.NSArray)


Someone to help me ? Thanks in advance

You should not redeclare upsList with the let


Array cannot be initialized like this.

You should either append to the array, or use the right initializer

upsList.append(upsFileAsURL! )


Array(repeating: upsFileAsURL!, count: 1)


Take care also to test upsFileAsURL for nil

What's the difference with this SO thread?: stackoverflow.com/questions/49728152/ambiguous-use-of-initcontentsofurl-in-swift-4-1


In Swift, there is no initializer: `NSArray.init(contentsOfURL:)`.

The Objective-C factory method `arrayWithContentsOfURL:` is not available in Swift, and `initWithContentsOfURL` is imported as `NSArray.init?(contentsOf:)`.

    func loadUpsValues () {
        print("loadUpsValues")
        let upsFileAsURL = URL(string: "Upslist.txt")
        let upsList = NSArray(contentsOf: upsFileAsURL!)
    }


If you want to write the array directly into the global `upsList`, than introducing the same name local:

    func loadUpsValues () {
        print("loadUpsValues")
        let upsFileAsURL = URL(string: "Upslist.txt")
        upsList = NSArray(contentsOf: upsFileAsURL!)! as! [Any]
    }

(I'm not sure using many forced unwrapping or forced casting is safe here.)


But you should better consider using `PropertyListSerialization`, if your `Upslist.txt` contains a plist-format array.

    func loadUpsValues() {
        let upsFileAsURL = URL(string: "Upslist.txt")
        do {
            let upsData = try Data(contentsOf: upsFileAsURL!)
            upsList = try PropertyListSerialization.propertyList(from: upsData, options: [], format: nil) as! [Any]
        } catch {
            print(error)
        }
    }
Ambiguous use of init(contentsOfURL:)
 
 
Q