2016-10-12 41 views
1

是否可以觀察添加到Set數據結構的值?觀察添加到Set的值 - Swift

我想要實現:

var storedStrings = Set<String>() { 
    didSet (value) { 
     // where value is a string that has been added to the Set 
    } 
} 

例子:
storedStrings.insert("hello")
didSet叫,作爲一種新的價值已被添加。

storedString.insert("world")
didSet再次調用。

storedString.insert("hello")
didSet不叫,作爲集已經包含字符串「hello」

回答

3

這可能是有點貴,但你仍然可以這樣做:

var storedStrings = Set<String>() { 
    didSet { 
     if storedStrings != oldValue { 
      print("storedStrings has changed") 
      let added = storedStrings.subtracting(oldValue) 
      print("added values: \(added)") 
      let removed = oldValue.subtracting(storedStrings) 
      print("removed values: \(removed)") 
     } 
    } 
} 
2

insert功能返回一個元組,其定義如下:(inserted: Bool, memberAfterInsert: Element)

因此,可以在插入時檢查新的唯一元素,而不是使用didSet

var storedStrings = Set<String>() 

var insertionResult = storedStrings.insert("Hello") 
if insertionResult.inserted { 
    print("Value inserted") // this is called 
} 

insertionResult = storedStrings.insert("Hello") 
if insertionResult.inserted { 
    print("Value inserted") // this isn't called 
} 
0

你可以實現自己的插件爲您設定的,這可能會仿效使用性質觀察員,利用這樣一個事實:Setinsert方法返回一個元組,其第一個成員的情況下,該元素false已經存在。

func insert(Element) 

插入該集合中給定元素,如果它不是已存在。

the language reference

例如爲:

struct Foo { 
    private var storedStrings = Set<String>() 

    mutating func insertNewStoredString(_ newString: String) { 
     if storedStrings.insert(newString).0 { 
      print("Inserted '\(newString)' into storedStrings") 
     } 
    } 
} 

var foo = Foo() 
foo.insertNewStoredString("hello") // Inserted 'hello' into storedStrings 
foo.insertNewStoredString("hello") 
foo.insertNewStoredString("world") // Inserted 'world' into storedStrings