Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't unsafeBitCast between types of different sizes in swift

when I try to find duplicates in array, I get the error "can't unsafeBitCast between types of different sizes". I find the duplicates following method.

    func uniq<S : SequenceType, T : Hashable where S.Generator.Element == T>(source: S) -> [T] {
    var buffer = [T]()
    var added = Set<T>()
    for elem in source {
        if !added.contains(elem) {
            buffer.append(elem)
            added.insert(elem)
        }
    }
    return buffer
}

func filter() {
    var arrayForSearch = mp3Files as! [String]
    var filteredArray = uniq(arrayForSearch)
    println("filtered array \(filteredArray)")
}

The method of find duplicates I knew on this link enter link description here. I use Xcode 6 and Swift 1.2

There is the array in this code.

var mp3Files: Array<String!>!
func exportData() {
    var generalURL: [AnyObject]?
    var arrayFiles: Array<NSURL!>!
    var directory = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)
    var urlFromDirectory = directory.first as! NSURL

    var file = fileManager.contentsOfDirectoryAtURL(urlFromDirectory, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, error: nil)!
    println("file \(file)")

    mp3Files = file.map(){ $0.lastPathComponent }.filter(){ $0.pathExtension == "mp3" }

  println("mp3 files  \(mp3Files)")
}

When I wrote this code in playground it works. An example

var array = ["Apple", "Mac", "iPhone", "iPad Air", "Apple", "Air", "Air"]
var filteredArray = Array(Set(array))

println(filteredArray)

How can I use it in my project?

like image 953
Alexander Khitev Avatar asked Jul 30 '15 07:07

Alexander Khitev


1 Answers

var mp3Files: Array<String!>!

Wow, that's a lot of exclamation points.... They're not needed.

var arrayForSearch = mp3Files as! [String]

And the type of mp3Files can never be the same as [String], so you can't force-cast between them (and would crash if it let you).

You're using implicitly unwrapped optionals way too often. They are only needed in some special cases. Just change mp3Files to [String] (in which case you won't need the as! at all; you shouldn't need as! very often either).

Similarly, arrayFiles (which you never use), should just be [NSURL], not Array<NSURL!>!.

like image 61
Rob Napier Avatar answered Oct 11 '22 10:10

Rob Napier