BitCast between types of different sizes in fast

when I try to find duplicates in an array, I get the error message "cannot notafeBitCast between types of different sizes". I find duplicates of the 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 for finding duplicates that I knew from this link is to enter a description of the link here . I am using Xcode 6 and Swift 1.2

There is an 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 on the playground, it works. 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?

+6
source share
2 answers
 var mp3Files: Array<String!>! 

Wow, this is a lot of exclamation points .... They are not needed.

 var arrayForSearch = mp3Files as! [String] 

And the type of mp3Files never be the same as [String] , so you cannot enforce between them (and crash if it allows you).

You too often use implicitly deployed options. They are needed only in some special cases. Just change mp3Files to [String] (in this case, you won’t need as! At all, you also won’t need as! ).

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

+2
source

Here I try the same code that you specified:

 import UIKit class ViewController: UIViewController { let strArr = ["a","b","a","d","f","f","b"] override func viewDidLoad() { super.viewDidLoad() filter() } 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 = strArr var newArr = uniq(arrayForSearch) println("filtered array \(newArr)") } } 

And OutPut in the console:

 filtered array [a, b, d, f] 

I am having a problem when you add an array to [String] to check it again.

0
source

All Articles