美文网首页
swift字符类型Character

swift字符类型Character

作者: flionel | 来源:发表于2018-11-10 14:42 被阅读35次

    1. 什么是字符?

    字符(Character)就是一个简单的符号(字母:abc, 数组:123等)。在swift种使用如下方式定义字符类型,

    let someCharacter: Character

    1.1 怎样定义字符并赋值

    为字符串赋值可以通过let aStr: String = " ",为字符赋值也是一样,let aCharacter: Character = " "但是一个字符变量只能包含一个空格。

    所以,如果你定义的变量包含多个字符,则应该使用String,而不是Character。

    1.1.1 举例1: 定义并赋值字符

    let someCharacter: Character = "H"
    let specialCharacter: Character = "@" // 特殊字符
    print(someCharacter)
    print(specialCharacter)
    

    1.1.2 举例2: 定义字符,并赋值多个字符(报错)

    如果尝试为一个字符变量赋值两个字符,则会报错,如下代码所示,

    let fialableCharacter: Character = @"H@"
    // 用String类型替代Character
    let okString: String = @"H@"
    

    1.2 使用unicode和转移字符创建Character

    开发这可以使用unicode创建特殊的字符类型,例如创建emoji表情字符。创建一个unicode需要使用转移字符,例如\u{n},n是十六进制的数字。如下代码所示,

    let heartShape: Character = "\u{2655}"
    print(heartShape)
    // 输出:♥
    

    在这个例子总,一个星形的字符使用U+2655 unicode创建。虽然"{2655}"包裹在双引号种,编译器并不会把它当作字符串,因为我们使用了“转移字符{u}”。一个转移字符并不代表它字面上的含义。

    2. 字符常用扩展属性和方法

    如下方法参考github的SwifterSwift项目,读者可查看了解更多的细节。

    import UIKit
    // MARK: - Properties
    public extension Character {
        /// Check if character is emoji
        /// - example: Character("😊").isEmoji -> true
        public var isEmoji: Bool {
            let scalarValue = String(self).unicodeScalars.first!.value
            switch scalarValue {
                case 0x3030, 0x00AE, 0x00A9, // Special Character > 特殊字符
                0x1D000...0x1F77F, // Emoticons > 情感符
                0x2100...0x27BF, // Misc symbols and Dingbats >
                0xFE00...0xFE0F, // Variation Selectors > 变异选择符
                0x1F900...0x1F9FF: // Supplemental Symbols and Pictographs > 补充的符号和象形文字
                return true
            default:
                return false
            }
        }
        
        /// Check if character is number
        /// - example: Character("1").isNummber
        public var isNumber: Bool {
            return Int(String(self)) != nil
        }
        
        /// Check if character is a letter(字母)
        /// - example: (1) Character("4").isLetter -> false, (2) Character("a").isLetter -> True
        public var isLetter: Bool {
            return String(self).rangeOfCharacter(from: .letters, options: .numeric, range: nil) != nil
        }
        
        /// Check if character is lowercased
        /// - example: (1) Character("a").isLowercased -> true, (2) Character("A").isLowercased -> false
        public var isLowercased: Bool {
            return String(self) == String(self).lowercased()
        }
        
        /// Check if character is uppercased
        /// - example: (1) Character("a").isUppercased -> true, (2) Character("A").isUppercased -> true
        public var isUppercased: Bool {
            return String(self) == String(self).uppercased()
        }
        
        /// Check if character is white space(空格)
        /// - example: (1) Character(" ").isWhiteSpace -> true, (2) Character("A").isWhiteSpace -> false
        public var isWhiteSpace: Bool {
            return String(self) == " "
        }
        
        /// Integer value from character (if applicable)
        /// - example: (1) Character("1").int -> 1, (2) Character("A").int -> nil
        public var int: Int? {
            return Int(String(self))
        }
        
        // String value from character
        public var string: String {
            return String(self)
        }
        
        /// Return the character lowercased
        public var lowercased: Character {
            return String(self).lowercased().first!
        }
        
        /// Return the character uppercased
        public var uppercased: Character {
            return String(self).uppercased().first!
        }
    }
    
    
    // MARK: - Methods
    public extension Character {
        /// Random character
    //    public static func randomAlphanumeric() -> Character {
    //        return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".randomElement()!
    //    }
    }
    
    // MARK: - Operater
    public extension Character {
        /// Repeat character multiple times
        /// - example: Character("=") * 10 -> "=========="
        /// - Parameters:
        ///     - lhs: charater to repeat.
        ///     - rhs: number of times to repeat character.
        /// - Returns: strign with charater repeated n times.
        public static func * (lhs: Character, rhs: Int) -> String {
            guard rhs > 0 else { return "" }
            return String(repeating: String(lhs), count: rhs)
        }
        
        /// Repeat character mltiple tiems
        /// - exmaple: 10 * Character("-") -> "----------"
        /// - Parameter:
        ///     - lhs: number of times to repeat character.
        ///     - rhs: character to repeat
        /// - Returns: string with character repeated n times
        public static func * (lhs: Int, rhs: Character) -> String {
            guard lhs > 0 else { return "" }
            return String(repeating: String(rhs), count: lhs)
        }
    }
    

    3. 参考链接

    相关文章

      网友评论

          本文标题:swift字符类型Character

          本文链接:https://www.haomeiwen.com/subject/qqvzxqtx.html