Swift_泛型(inout、泛型函数<TypeName>..)

本文介绍了Swift中泛型的使用,包括显式泛型和隐式泛型,通过实例展示了如何在结构体中声明泛型类型,并提供了泛型函数的用法,如`typeFunc`和`hideFunc`等。同时,还演示了如何在泛型结构体`structType`中操作数组和字典,以及泛型在实际代码中的应用。
/*!3、泛型类型*/
//给一个结构体声明泛型类型
struct structType<TypeName> {
    
    var array:[TypeName] = [TypeName]()
    var dic = [String:TypeName]()
    
    //数组增加、删
    mutating func appenArray(_ some:TypeName) {
        array.append(some)
    }
    mutating func removArrayIndex(_ index:Int){
        array.remove(at: index)
    }
    
    
    
    //字典增加、
    mutating func setValueDic(_ key:String,_ value:TypeName){
        dic[key] = value
    }
    mutating func removDic(_ key:String,_ value:TypeName) -> Bool {
        let val = dic.removeValue(forKey: key)
        if (val == nil) {return false} ; return true
        
    }
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //1
        var x = 110
        var y = 330
        typeFunc(xx: &x, yy: &y)
        typeFunc2(&x, &y)
        
        
        //2
        var s = "fdsf"
        var s1 = "dsfw"
        var s2 = 30
        hideFunc(&s, &s1)
        hideFunc11(s, s1) //编译时错误,泛型函数只声明了<一个类型> ,所以传参只能是相同类型
        hideFunc2("first", 999)
        
        
        //3
        var st = structType<Int>()
        print(st.array,st.dic)  //[] [:]

        st.appenArray(10)
        st.appenArray(11)
        print(st.array)         //[10, 11]
        st.removArrayIndex(0)   //[11]
        print(st.array)
        st.array.enumerated()
        st.setValueDic("one", 32413)
        st.setValueDic("tow", 534260)
        print(st.dic)            //["one": 32413, "tow": 534260] 
        let dicremob = st.removDic("one", 0)
        print(st.dic)            //["tow": 534260]



        
    }

    
    
    /*!1、显式泛型*/
    func typeFunc(xx x:inout Int, yy y:inout Int) {
        
        let value = x
        x = y
        y = value
        
        
    }
    func typeFunc2(_ x:inout Int, _ y:inout Int) {
        
        let value = x
        x = y
        y = value
    }
    
    
    
    /*!2、隐式泛型*/
    func hideFunc<Ts>(_ x:inout Ts,_ y:inout Ts) {
        let value = y
        y = x
        x = value
    }
    func hideFunc11<Ts>(_ x:Ts,_ y:Ts) {
        print("\(x)=\(y)")
    }
    func hideFunc2<key,value>(_ x:key,_ y:value){
        
        print("\(x)=\(y)")
    }
    func hideFunc3<key,value>(_ x:key,_ y:value,_ z:Double){
        
        print("\(x)=\(y) \(z)")
    }
    

}

In file included from /usr/local/include/fmt/format.h:41, from /usr/local/include/fmt/chrono.h:23, from /home/qxn/sp_vision_25-main/tasks/auto_aim/yolos/yolo11.cpp:3: /usr/local/include/fmt/base.h: In instantiation of ‘constexpr fmt::v11::detail::value<Context>::value(const T&, fmt::v11::detail::custom_tag) [with T = auto_aim::ArmorName; typename std::enable_if<(! has_formatter<T, typename Context::char_type>()), int>::type <anonymous> = 0; Context = fmt::v11::context]’: /usr/local/include/fmt/base.h:2235:65: required from ‘fmt::v11::detail::value<Context>::value(T&) [with T = const auto_aim::ArmorName; typename std::enable_if<(std::integral_constant<bool, (((((((std::is_class<T>::value || std::is_enum<T>::value) || std::is_union<T>::value) || std::is_array<_Up>::value) && (! fmt::v11::detail::has_to_string_view<T, void>::value)) && (! fmt::v11::detail::is_named_arg<T>::value)) && (! fmt::v11::detail::use_format_as<T>::value)) && (! fmt::v11::detail::use_format_as_member<typename std::remove_const<T>::type, std::integral_constant<bool, true> >::value))>::value || (!1)), int>::type <anonymous> = 0; Context = fmt::v11::context]’ /usr/local/include/fmt/format.h:4200:17: required from ‘std::string fmt::v11::format(format_string<T ...>, T&& ...) [with T = {const std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&, const auto_aim::ArmorName&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&}; std::string = std::__cxx11::basic_string<char>; format_string<T ...> = fstring<const std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&, const auto_aim::ArmorName&, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&>]’ /home/qxn/sp_vision_25-main/tasks/auto_aim/yolos/yolo11.cpp:261:30: required from here /usr/local/include/fmt/base.h:2262:45: error: ‘fmt::v11::detail::type_is_unformattable_for<auto_aim::ArmorName, char> _’ ha
最新发布
10-18
你看看怎么改好 /* * (C) 2007-2010 Taobao Inc. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * * Version: $Id$ * * Authors: * duolong <duolong@taobao.com> * */ #ifndef __TBSYS_BYTEBUFFER_H__ #define __TBSYS_BYTEBUFFER_H__ #include "tbsys.h" namespace tbutil { /** * ByteBuffer 类似于Java里面的同名类,是一个二进制流的封装 * * ByteBuffer必须预先分配好固定大小的一块缓冲,当put或get的位置超过 * 初始设定的大小,会抛出 ByteBuffer::out_of_range 异常 * ByteBuffer 负责管理缓冲的内存,但是如果你使用wrap方法,则内存由你 * 自己管理,所以使用wrap的时候一定知道你自己必须为自己的内存负责. * * ByteBuffer 是流的形式,支持 << 和 >>操作符 * put和get方法是流操作符的实现,分别是放入和取出一个特定类的元素 * 这两个方法都会导致内部的position指针移动 * * peek 方法同get一样取出当前位置的元素,但是不移动position指针 * */ class ByteBuffer { public: class out_of_range : public std::exception { public: out_of_range(uint32_t p, uint32_t l, uint32_t s); virtual ~out_of_range() throw() {} virtual const char* what() const throw() ; private: static const uint32_t MAX_ERROR_MSG_LEN = 256; char errmsg_[MAX_ERROR_MSG_LEN]; }; public: explicit ByteBuffer() ; explicit ByteBuffer(uint32_t size); explicit ByteBuffer(const ByteBuffer& rhs); ByteBuffer(const char* data, uint32_t offset, uint32_t size); ByteBuffer & assign(const char* data, uint32_t offset, uint32_t size); ByteBuffer & wrap(char* data, uint32_t offset, uint32_t size); ByteBuffer & operator=(const ByteBuffer& rhs); virtual ~ByteBuffer(); public: // generic put & get template <typename T> ByteBuffer & put (const T & e) throw (out_of_range); template <typename T> ByteBuffer & get (T & e) throw (out_of_range); template <typename T> ByteBuffer & put (const std::vector<T> & v) throw (out_of_range) ; template <typename T> ByteBuffer & get (std::vector<T> & v) throw (out_of_range); template <typename T> ByteBuffer & operator<<(const T &e) throw (out_of_range) { return put(e); } template <typename T> ByteBuffer & operator>>(T &e) throw (out_of_range) { return get(e); } template <typename T> const ByteBuffer & peek (T & e) const throw (out_of_range); template <typename T> T get () throw (out_of_range); // specialize put & get with std::string ByteBuffer & put(const std::string & e) throw (out_of_range) { return putString(e); } ByteBuffer & get(std::string & e) throw (out_of_range) { return getString(e); } ByteBuffer & putString(const std::string & v) throw (out_of_range); ByteBuffer & getString(std::string & v) throw (out_of_range); // get data_ directly.. virtual ByteBuffer & put(const char* src, uint32_t offset, uint32_t size) throw (out_of_range); virtual ByteBuffer & get(char* dst, uint32_t offset, uint32_t size) throw (out_of_range); // relative get method, from index of data_ ByteBuffer & get(int index, char* dst, uint32_t offset, uint32_t size) throw (out_of_range); // fetch data_ directly, use them very carefully ByteBuffer & getRef(int index, const char* &dst, uint32_t size) throw (out_of_range); const ByteBuffer & rawData(int index, const char* &dst, uint32_t size) const throw (out_of_range) ; template <typename T> ByteBuffer & getRef(int index, T* &dst) throw (out_of_range); template <typename T> ByteBuffer & getRef(int index, const T* &dst) throw (out_of_range); public: void reset(); void reset(uint32_t size); uint32_t position(uint32_t p) throw (ByteBuffer::out_of_range); uint32_t position() const { return position_; } uint32_t size() const { return size_; } int32_t remaining() const { return size_ - position_; } protected: char* allocate(uint32_t size) const; void free(); ByteBuffer & copy(const char* data, uint32_t offset, uint32_t length); protected: char* data_; uint32_t size_; uint32_t position_; bool own_; }; template <typename T> ByteBuffer & ByteBuffer::put(const T & e) throw (ByteBuffer::out_of_range) { if (position_ + sizeof(T) > size_) throw out_of_range(position_, sizeof(T), size_); memcpy(data_ + position_, &e, sizeof(T)); position_ += sizeof(T); return *this; } template <typename T> ByteBuffer & ByteBuffer::get(T & e) throw (ByteBuffer::out_of_range) { if (position_ + sizeof(T) > size_) throw out_of_range(position_, sizeof(T), size_); peek(e); position_ += sizeof(T); return *this; } template <typename T> T ByteBuffer::get() throw (ByteBuffer::out_of_range) { T e; get(e); return e; } template <typename T> const ByteBuffer & ByteBuffer::peek(T & e) const throw (ByteBuffer::out_of_range) { if (position_ + sizeof(T) > size_) throw out_of_range(position_, sizeof(T), size_); memcpy(&e, data_ + position_, sizeof(T)); return *this; } template <typename T> ByteBuffer & ByteBuffer::put(const std::vector<T> & v) throw (ByteBuffer::out_of_range) { put(v.size()); for (uint32_t i = 0; i < v.size(); ++i) { put(v[i]); } return *this; } template <typename T> ByteBuffer & ByteBuffer::get(std::vector<T> & v) throw (ByteBuffer::out_of_range) { uint32_t size; get(size); T e; for (uint32_t i = 0; i < size; ++i) { get(e); v.push_back(e); } return *this; } template <typename T> ByteBuffer & ByteBuffer::getRef(int index, T* &dst) throw (out_of_range) { const char* ref = 0; getRef(index, ref, sizeof(T)); dst = (T*) ref; return *this; } template <typename T> ByteBuffer & ByteBuffer::getRef(int index, const T* &dst) throw (out_of_range) { const char* ref = 0; getRef(index, ref, sizeof(T)); dst = (const T*) ref; return *this; } } // end namespace tfs #endif //__BYTEBUFFER_H__
08-02
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值