Swift switch statement for matching substrings of a String

前端 未结 7 1585
时光说笑
时光说笑 2021-01-01 15:55

Im trying to ask for some values from a variable. The variable is going to have the description of the weather and i want to ask for specific words in order to show differen

7条回答
  •  悲哀的现实
    2021-01-01 16:46

    If you do this a lot, you can implement a custom ~= operator that defines sub-string matching:

    import Foundation
    
    public struct SubstringMatchSource {
        private let wrapped: String
    
        public init(wrapping wrapped: String) {
            self.wrapped = wrapped
        }
    
        public func contains(_ substring: String) -> Bool {
            return self.wrapped.contains(substring)
        }
    
        public static func ~= (substring: String, source: SubstringMatchSource) -> Bool {
            return source.contains(substring)
        }
    }
    
    extension String {
        var substrings: SubstringMatchSource {
            return SubstringMatchSource(wrapping: self)
        }
    }
    
    switch "abcdefghi".substrings {
        case "def": // calls `"def" ~= "abcdefghi".substrings`
            print("Found substring: def") 
        case "some other potential substring":
            print("Found \"some other potential substring\"")
        default: print("No substring matches found")
    }
    

提交回复
热议问题