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?
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!>!
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With