美文网首页
Swift 中打印实例输出自定义字符串

Swift 中打印实例输出自定义字符串

作者: 张科_Zack | 来源:发表于2021-06-08 15:02 被阅读0次

    Swift 中打印实例输出自定义字符串

    Swift 中如果直接通过 print 方法 打印一个类的实例多数情况会打印出实例的类名。但是如果我们想打印出具体属性值,则通过执行 CustomStringConvertible 协议并实现其协议计算属性 description 即可。
    以下为具体示例代码(示例代码运行在 Xcode PlayGround):

    // 1. 首先 申明一个 Person 类
    class Person {
        
        enum Gender {
            case Male
            case Female
            case Other
        }
        var firstName = ""
        var lastName = ""
        var fullName: String {
            firstName + lastName
        }
        var gender: Gender = .Other
        var age: Int = 0
        var interest: String = ""
        init(firstName: String,
             lastName: String,
             gender: Gender,
             age: Int,
             interest: String) {
            self.firstName = firstName
            self.lastName = lastName
            self.gender = gender
            self.age = age
            self.interest = interest
        }
    
    }
    
    2. 实例化一个 Person 对象 tom 并打印。
    let tom = Person(firstName: "Tom", lastName: "Wang", gender: .Male, age: 25, interest: "basketball")
    print(tom)
    
    3. 打印结果为
    __lldb_expr_84.Person
    
    4. Person 类执行 CustomStringConvertible 协议并实现 description 计算属性。
    
    class Person: CustomStringConvertible {
        var description: String {
            var genderString = ""
            switch gender {
            case .Female:
                genderString = "Female"
            case .Male:
                genderString = "Male"
            default:
                genderString = "Other"
    
            }
            return """
                Class Name [Person]
                Property:
                firstName:\(firstName)
                lastName:\(lastName)
                fullName:\(fullName)
                gender:\(genderString)
                age:\(age)
                interest:\(interest)
                """
        }
    }
    
    5. 重新运行代码则输出结果为
    Class Name [Person]
    Property:
    firstName:Tom
    lastName:Wang
    fullName:TomWang
    gender:Male
    age:25
    interest:basketball
    
    

    相关文章

      网友评论

          本文标题:Swift 中打印实例输出自定义字符串

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