我需要驗證字符串的長度。爲字符計數的允許值包括:將單個整數值視爲Swift中的一個範圍
- 6 - 9個字符
- 12個字符
- 15個字符
所有字符串與不同的字符計數是無效的。因此,我想創建接受一個數範圍,並評估串的夫特功能:
extension String {
func evaluateLength(validCharacterCounts: Range<Int>...) -> Bool {
// Implementation
}
}
現在我可以調用該函數用於單個Int
範圍:
"Live long and prosper".evaluateLength(validCharacterCounts: 6..<10)
和多個Int
範圍:
"Live long and prosper".evaluateLength(validCharacterCounts: 6..<10, 15..<20)
但我不能用單一的,分離的整數值調用函數:
"Live long and prosper".evaluateLength(validCharacterCounts: 6..<10, 12, 15)
因爲12
和15
被分類爲Int
而不是Range<Int>
。
Swift compile error: Cannot convert value of type 'Int' to expected argument type 'Range'
有沒有一種方式來對待一個整數,如斯威夫特一個Range
,像自動澆鑄成Range<Int>
?
(畢竟5
相當於5..<6
,所以從數學上講5
是一個範圍爲好。)
另一種方法是傳遞一個'IndexSet'類型的參數。 –
你的意思是像'evaluateLength(validCharacterCounts:IndexSet(6 .. <10),IndexSet(12,15))'?或者是否有一個帶有'IndexSet'的整潔的解決方案,它允許類似上述的語法? – Mischa