ios - Generic Swift struct: Segmentation fault: 11 -
i trying implement struct generic type conforms hashable protocol. can me understand why getting "segmentation fault: 11" error following code.
i appreciate insights regarding this.
struct pmf<element: hashable> { typealias distribution = [element : float] fileprivate var normalized = false fileprivate var distribution:[element : float] = [ : ] { didset { self.normalized = false } } } extension pmf { init(values: [element], withprobs probs: [float]) { pair in zip(values, probs) { self.distribution[pair.0] = pair.1 } } var probdist: distribution { mutating { if !normalized { self.normalize() } return self.distribution } } subscript(value: element) -> float? { mutating { if !normalized { self.normalize() } return self.distribution[value] } set(prob) { self.distribution[value] = prob } } mutating func normalize() { (key, val) in self.distribution { self.distribution[key] = val / float(self.distribution.count) } } } var pp = pmf<string>() pp["one"] = 4 pp["two"] = 5 pp["three"] = 5 print(pp)
seems need little trick define initializer value type in extension:
add 1 line init(values:withprobs:)
shown below:
init(values: [element], withprobs probs: [float]) { self.init() //<- pair in zip(values, probs) { self.distribution[pair.0] = pair.1 } }
anyway compilers should not crash segfault 11. if source code has fault in it.
you'd better send bug report apple, or swift.org.
Comments
Post a Comment