2017-05-08 46 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

生病现在试试看,谢谢你的回答 –