๐Ÿžhas non-Sendable type

โŸฉ

Swift โŸฉ Concurrency โŸฉ Sendable โŸฉ ๐Ÿž has non-Sendable type

Stored property 'shape' of 'Sendable'-conforming struct 'MyAnyShape' has non-sendable type '(CGRect)->Path'

๐Ÿ‘‰ ChatGPT conversation

import SwiftUI

// โญ๏ธ Shape is Sendable
struct MyAnyShape: Shape {
    
    // โญ๏ธ properties must be Sendable too.
    private let shape: (CGRect) -> Path   // ๐Ÿž error
    
    init<S: Shape>(_ wrapped: S) {
        self.shape = { rect in
            wrapped.path(in: rect)
        }
    }
    
    func path(in rect: CGRect) -> Path {
        shape(rect)
    }
}

้Œฏ่ชคๅŽŸๅ› 

  1. MyAnyShape ้ตๅพช Shape๏ผŒไฝ† Shape ้šฑๅซ้ตๅพช Sendable ็š„่ฆๅฎš(็”จๆ–ผ Concurrency ็š„ๅฎ‰ๅ…จไฟ้šœ๏ผ‰ใ€‚

    • Sendable ่ฆๆฑ‚ struct ไธญๆ‰€ๆœ‰ๅฑฌๆ€งไนŸๅฟ…้ ˆๆ˜ฏ Sendableใ€‚

    • ไฝ† shape ๅฑฌๆ€งๆ˜ฏ้–‰ๅŒ…(closure)๏ผŒไธฆไธ่‡ชๅ‹•็ฌฆๅˆ Sendable๏ผŒๅ› ็‚บๅฎƒๅฏ่ƒฝๆ•็ฒ้ž Sendable ็š„ๅ€ผใ€‚

  2. Swift Concurrency ็š„ๅฝฑ้Ÿฟ

    • ๅœจ Swift 5.5 ๆˆ–ๆ›ด้ซ˜็‰ˆๆœฌไธญ๏ผŒไธฆ่กŒ็จ‹ๅผ่จญ่จˆ(Concurrency)ๆœƒๅฐๆŸไบ›้กžๅž‹้€ฒ่กŒๆ›ดๅšดๆ ผ็š„ๅž‹ๅˆฅๆชขๆŸฅ๏ผŒ็‰นๅˆฅๆ˜ฏ็”จๆ–ผ @Sendable ้–‰ๅŒ…็š„ๆƒ…ๆณใ€‚

่งฃๆฑบๆ–นๆกˆ

ๆ–นๆกˆไธ€๏ผš็›ดๆŽฅๅ„ฒๅญ˜ Shape ๅฏฆไพ‹(wrappedShape)๏ผŒ่€Œไธๆ˜ฏ้–‰ๅŒ…(closure)๏ผŒๅฎŒๅ…จ้ฟ้–‹ Sendable ็š„ๅ•้กŒใ€‚้€™ๆจฃ็š„ๅฏซๆณ•ๅ…ทๆœ‰่ผƒๅคง็š„้ˆๆดปๆ€ง๏ผŒๅฆ‚ๆžœไฝ ๆœ‰ๅพˆๅคš็จฎ้กž็š„ Shape๏ผŒๅปบ่ญฐ็”จๆญคๅฏซๆณ•ใ€‚

import SwiftUI

struct MyAnyShape: Shape {

    // โญ๏ธ ็›ดๆŽฅๅ„ฒๅญ˜ Shape ๅฏฆไพ‹
    private var wrappedShape: any Shape

    init<S: Shape>(_ wrapped: S) {
        self.wrappedShape = wrapped
    }

    func path(in rect: CGRect) -> Path {
        wrappedShape.path(in: rect)
    }
}

Last updated