2017-05-08 44 views
0

相匹配的字符串我有四根弦刪除對象對象的字符串在一個單獨的陣列

class Post: NSObject { 
    var author: String! 
    var postID: String! 
    var pathToImage: String! 
    var userID: String! 
} 

一個NSObject I類也有一個單獨的類的ViewController具有抓取功能從火力職位。我有一個名爲posts = [Post]()的數組,其中填充了一個單獨的函數,通過firebase並獲取每張照片的數據。我也有一個名爲removeArray的數組,它是字符串數組,其中的字符串是某些帖子的postID。現在這是我的問題,我試圖通過removeArray循環,檢查removeArray =中的每一個是否與posts.postID中的每一個相同,並檢查它們是否相等。然後,我刪除每個在posts.postID後,或者我創建一個新的數組,這是post-postID的removeArray。這裏是我的代碼現在不起作用,它只是保持職位。

if posts != nil { 
    if var array = UserDefaults.standard.object(forKey: "removeArray") as? [String] { 
     for each in posts { 
      for one in array { 
       if one == each.postID { 
        new.append(each) 
       } 
      } 
     } 

     return self.posts.count 
    } 
} 

所以,如果你有任何想法如何採取一個字符串數組,檢查是否該字符串,如果eqaul到的objects.postID數組字符串,並從數組中刪除該對象是否相等。我試圖研究一種方法來過濾它,但到目前爲止沒有。請給我一些反饋。由於 我的問題= http://imgur.com/a/m5CiY

回答

0
var posts = [p1,p2,p3,p4,p5] 
let array = ["aaa","bbb"] 
var new:Array<Post> = [] 

for each in posts { 
    for one in array { 
     if one == each.postID { 
      new.append(each) 
     } 
    } 
} 

print("This objects should be remvoed: \(new)") 
posts = Array(Set(posts).subtracting(new)) 
print("After removing matching objects: \(posts)") 
+0

訊息不是一個字符串數組,而其NSObjects的陣列,如在上面的圖像,後級示出。 var posts = [Post]() –

+0

@RandyWindin,更新了答案。請立即檢查。 – Hemang

+0

嗯,這看起來不錯,讓我試試 –

0

你可以使用reduce(_:_:)

class Country { 

    var name: String! 

    init(name: String) { 

     self.name = name 
    } 
} 

let countries = [Country(name: "Norway"), Country(name: "Sweden"), Country(name: "Denmark"), Country(name: "Finland"), Country(name: "Iceland")] 

let scandinavianCountries = ["Norway", "Sweden", "Denmark"] 

// Store the objects you are removing here 
var nonScandinavianCountries: [Country]? 

let scandinavia = countries.reduce([Country](), { 
    result, country in 

    // Assign result to a temporary variable since result is immutable 
    var temp = result 

    // This if condition works as a filter between the countries array and the result of the reduce function. 
    if scandinavianCountries.contains(country.name) { 

     temp.append(country) 
    } else { 

     if nonScandinavianCountries == nil { 
      // We've reached a point where we need to allocate memory for the nonScandinavianContries array. Instantiate it before we append to it! 
      nonScandinavianCountries = [] 
     } 

     nonScandinavianCountries!.append(country) 
    } 

    return temp 
}) 

scandinavia.count // 3 

nonScandinavianCountries?.count // 2 

Resouces: https://developer.apple.com/reference/swift/array/2298686-reduce

+0

生病現在試試看,謝謝你的回答 –