You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何对比Swift String与NSAttributedString以确保代码可编译?

Great question! Let's break down the key differences between Swift's native String and NSAttributedString, then jump into a working code example that demonstrates how they behave side by side.

Core Differences Between Swift String and NSAttributedString

Here are the most important distinctions to keep in mind:

  • Purpose & Content:
    • String is Swift's built-in type for plain, unstyled text—it only contains character data, no formatting information.
    • NSAttributedString (part of the Foundation framework) wraps a plain string plus a collection of attributes (font, color, underline, paragraph styles, etc.) that define styling for specific ranges of the text.
  • Type System Integration:
    • String is deeply integrated with Swift's type system, supporting native features like Unicode correctness, string interpolation, and pattern matching.
    • NSAttributedString is a Cocoa/Cocoa Touch class, so it works seamlessly with UIKit/AppKit components (like UILabel, UITextView), but requires bridging when used with pure Swift code.
  • Mutability:
    • For String, you use var for mutable instances and let for immutable ones.
    • For attributed strings, there's a dedicated NSMutableAttributedString subclass for modifying content or attributes after creation.
Working Compilation Example

This code runs in an iOS playground or a standard iOS project, and visually shows the difference between plain and attributed text:

import UIKit
import PlaygroundSupport

// 1. Create a plain Swift String (no styling)
let plainText: String = "Hello, Swift & Attributed Strings!"

// 2. Build an NSAttributedString with multiple styles
let styledAttributedText: NSAttributedString = {
    let baseString = "Hello, Swift & Attributed Strings!"
    let mutableAttributedString = NSMutableAttributedString(string: baseString)
    
    // Define styling attributes
    let boldFont = UIFont.boldSystemFont(ofSize: 18)
    let redTextColor = UIColor.systemRed
    let underlineStyle = NSUnderlineStyle.single.rawValue
    
    // Apply attributes to specific text ranges
    // Bold the "Hello," substring
    mutableAttributedString.addAttribute(
        .font, 
        value: boldFont, 
        range: NSRange(location: 0, length: 6)
    )
    // Color "Swift" red
    mutableAttributedString.addAttribute(
        .foregroundColor, 
        value: redTextColor, 
        range: NSRange(location: 7, length: 5)
    )
    // Underline "Attributed Strings"
    mutableAttributedString.addAttribute(
        .underlineStyle, 
        value: underlineStyle, 
        range: NSRange(location: 13, length: 18)
    )
    
    return mutableAttributedString
}()

// 3. Create a simple UI to display both text types
let containerView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 220))
containerView.backgroundColor = .systemBackground

// Label for plain text
let plainLabel = UILabel(frame: CGRect(x: 20, y: 40, width: 280, height: 40))
plainLabel.text = plainText
plainLabel.font = UIFont.systemFont(ofSize: 16)
containerView.addSubview(plainLabel)

// Label for attributed text
let attributedLabel = UILabel(frame: CGRect(x: 20, y: 100, width: 280, height: 80))
attributedLabel.attributedText = styledAttributedText
attributedLabel.numberOfLines = 0 // Allow line wrapping
containerView.addSubview(attributedLabel)

// Show the UI in the playground
PlaygroundPage.current.liveView = containerView

What this code does:

  • The plainText variable is a standard Swift String—when displayed, it uses the label's default font and color with no special styling.
  • The styledAttributedText uses NSMutableAttributedString to apply three different styles to specific parts of the same base string.
  • We add both text types to UILabels so you can directly compare the plain vs. styled output.

内容的提问来源于stack exchange,提问作者Eric Armstrong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:17:53