首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >你能在Swift中重载类型转换操作符吗?

你能在Swift中重载类型转换操作符吗?
EN

Stack Overflow用户
提问于 2018-06-08 04:07:35
回答 1查看 1.4K关注 0票数 5

我想在Swift中实现已知类型之间的自动类型转换。C#的方法是重载类型转换操作符。如果我希望我的X类型可以与string交叉赋值,我可以这样写:

public class X 
{
     public static implicit operator string(X value)
     {
          return value.ToString();
     }

     public static implicit operator X(string value)
     {
          return new X(value);
     }
}

在那之后,我可以写一些类似这样的东西:

string s = new X();
X myObj = s;

它们会被自动转换。在Swift中,这有可能吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-08 05:37:10

不,该语言没有为自定义类型提供这样的功能。Objective-C集合和Swift集合之间存在桥梁,但这是内置的,不能自定义。

// Swift array of `String` elements
let swiftArray: [String] = ["Bob", "John"] 

// Obj-C array of `NSString` elements, but element type information 
// is not known to the compiler, so it behaves like an opaque NSArray
let nsArray: NSArray = ["Kate", "Betty"] 

// Obj-C array of an `NSString` and an `NSNumber`, element type
// information is not known to the compiler
let heterogeneousNSArray: NSArray = ["World", 3]

// Casting with `as` is enough since we're going from Swift array to NSArray 
let castedNSArray: NSArray = swiftArray as NSArray

// Force casting with `as!` is required as element type information 
// of Obj-C array can not be known at compile time
let castedSwiftArray: [String] = nsArray as! [String]

// Obj-C arrays can not contain primitive data types and can only 
// contain objects, so we can cast with `as` without requiring a 
// force-cast with `!` if we want to cast to [AnyObject]
let heterogeneousCastedNSArray: [AnyObject] = heterogeneousNSArray as [AnyObject]

有关类型转换的文档可以在here中找到。

我认为你可以用初始化器实现你想要做的事情。

extension X {
    init(string: String) {
        self = X(string)
    }        
}

extension String {
    init(x: X) {
        // toString is implemented elsewhere
        self = x.toString
    }        
}

let x = X()
let string = "Bobby"

let xFromString: X = X(string: string)
let stringFromX: String = String(x: x)

与您的问题没有直接关系,但是还有一系列以ExpressibleBy...开头的协议,使您可以执行以下操作:假设我们希望从整型文字初始化字符串。我们可以通过遵循和实现ExpressibleByIntegerLiteral来做到这一点

// Strings can not be initialized directly from integer literals
let s1: String = 3 // Error: Can not convert value of type 'Int' to specified type 'String'

// Conform to `ExpressibleByIntegerLiteral` and implement it
extension String: ExpressibleByIntegerLiteral {
  public init(integerLiteral value: Int) {
    // String has an initializer that takes an Int, we can use that to 
    // create a string
    self = String(value)
  }
}

// No error, s2 is the string "4"
let s2: String = 4 

可以在here中找到ExpressibleByStringLiteral的一个很好的用例。

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50749435

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档