2017-01-24 7 views
6

के क्रम में एक CGPoint सरणी व्यवस्था करने के लिए मैंने देखा this post जो कैसे निम्नलिखित तरीके से पूर्णांकों के लिए एक सरणी की सबसे लगातार मूल्य प्राप्त करने के कहते हैं, से पता चला है:कैसे सबसे लगातार अंक

let myArray = [4, 4, 4, 3, 3, 3, 4, 6, 6, 5, 5, 2] 

// Create dictionary to map value to count 
var counts = [Int: Int]() 

// Count the values with using forEach  
myArray.forEach { counts[$0] = (counts[$0] ?? 0) + 1 } 

// Find the most frequent value and its count with max(isOrderedBefore:)  
if let (value, count) = counts.max(isOrderedBefore: {$0.1 < $1.1}) { 
    print("\(value) occurs \(count) times") 
} 

मैं चाहता हूँ CGPoints की सरणी के लिए एक ही परिणाम प्राप्त करने के लिए, यह थोड़ा अलग है। मैं एक ही कोड का उपयोग करने की कोशिश की और एक त्रुटि मिली: लाइन

var counts = [CGPoint: Int]() 

और एक त्रुटि

Value of type 'CGPoint' has no member '1' 

लाइन पर पर

Type 'CGPoint' does not conform to protocol 'Hashable' 

if let (value, count) = counts.max(isOrderedBefore: {$0.1 < $1.1}) { 

कैसे कर सकते हैं मैं CGPoint सरणी के क्रम में व्यवस्थित करता हूं आवृत्ति और प्रिंट कहते हैं, मूल्य के साथ एक tuple और यह प्रकट होने की संख्या?

+1

यहाँ http://codereview.stackexchange.com: counts के शब्दकोश में कुंजी के रूप में अपने CGPoint वस्तुओं की डिबग वर्णन (String) का उपयोग/प्रश्न/148763/विस्तार-सीजीपॉइंट-टू-कॉन्फॉर्म-टू-हैशबल सीजीपॉइंट हैशबल बनाने के बारे में कुछ विचार हैं। –

+0

यदि निर्देशांक पूर्णांक नहीं हैं तो बाइनरी फ़्लोटिंग पॉइंट संख्याओं की सीमित सटीकता एक समस्या बन सकती है। उदाहरण के तौर पर, 'CGPoint (x: 0.1 + 0.2, y: 0) 'CGPoint (x: 0.3, y: 0)' से * अलग * है। –

+1

@MartinR शब्दकोश बनाने के लिए केवल CGPoint डीबग डिस्क्रिप्शन का उपयोग क्यों न करें? 'var counts = [स्ट्रिंग: Int]() myArray.forEach {गणना [$ 0.debugDescription] = (गणना [$ 0.debugDescription] ?? 0) + 1} अगर चलो (मान, गिनती) = counts.max (द्वारा: {$ 0.value <$ 1.value}) { प्रिंट ("\ (मान) होता है \ (गिनती) बार") } 'https://gist.github.com/leodabus/b109b2ca9633c44974399a771690fe1d –

उत्तर

0

क्या त्रुटि की इस पंक्ति का अर्थ है:

Type 'CGPoint' does not conform to protocol 'Hashable'

है कि आप एक शब्दकोश में कुंजी के रूप में CGPoint वस्तुओं का उपयोग नहीं कर सकते हैं।

वैकल्पिक हल सिंह Dabus टिप्पणी में उल्लेख किया है अच्छी तरह से काम करना चाहिए:

var counts = [String: Int]() 

myArray.forEach { counts[$0.debugDescription] = (counts[$0.debugDescription] ?? 0) + 1 } 

if let (value, count) = counts.max(by: {$0.value < $1.value}) { 
    print("\(value) occurs \(count) times") 
} 
संबंधित मुद्दे